I have 10 dataframes (ex: dfc,df1,df2,df3,df4,dft1,dft2,dft3,dft4,dft5). I want to check the length of each dataframe. If the length of dataframe is less than 2, I want to add the name of that dataframe to an empty list. How can I do this?
You can store the dataframes in a dictionary using their names as keys and then iterate over the dictionary:
dic = {'df1': df1,'df2': df2,'df3': df3,'df4': df4}
d = []
for k, v in dic.items():
if len(v) < 2:
d.append(k)
print(d)
You can also use aa list comprehension instead of the for loop:
dic = {'df1': df1,'df2': df2,'df3': df3,'df4': df4}
d = [k for k, v in dic.items() if len(v) < 2]
If I understand you correct, you want to create a list of the short dataframe-list.
I would do it like this:
dataframes = ['d','df1','df2','df3','df4','dft1','dft2','dft3','dft4','dft5']
short_dataframe = [] # the empy list.
for frame in dataframes:
if len(frame) < 2:
short_dataframe.append(frame) # adds the frame to the empty list
print(short_dataframe)
result of the print = ['d']
Related
I want to count identical values in my lists in list.
already I coded it:
id_list = [['cat','animal'],['snake','animal'], ['rose','flower'], ['tomato','vegetable']]
duplicates = []
for x in range(len(id_list)):
if id_list.count(id_list[x][1]) >= 2:
duplicates.append(id_list[x][1])
print(duplicates)
I think it don't work becouse the count is counting id[x][1] and don't seen any other values in rest of lists.
If there any way to count my lists instead of value of that list but leaning on this value?
Thank for all help and advice
Have a nice day!
You can get the count of all the elements from your list in a dictionary like this:
>>> id_list = [['cat','animal'],['snake','animal'], ['rose','flower'], ['tomato','vegetable']]
>>> {k: sum(id_list, []).count(k) for k in sum(id_list, [])}
{'cat': 1, 'animal': 2, 'snake': 1, 'rose': 1, 'flower': 1, 'tomato': 1, 'vegetable': 1}
You can extract the elements whose value (count) is greater than 1 to identify as duplicates.
Explanation: sum(id_list, []) basically flattens a list of lists, this would work for any number of elements inside your inner lists. sum(id_list, []).count(k) stores the count of every k inside this flattened list and stores it in a dictionary with k as key and the count as value. You can iterate this dictionary now and select only those elements whose count is greater than, let’s say 1:
my_dict = {k: sum(id_list, []).count(k) for k in sum(id_list, [])}
for key, count in my_dict.items():
if count > 1:
print(key)
or create the dictionary directly by:
flat_list = sum(id_list, [])
>>> {k: flat_list.count(k) for k in flat_list if flat_list.count(k) > 1}
{'animal': 2}
How about this:
id_list = [['cat','animal'],['snake','animal'], ['rose','flower'], ['tomato','vegetable']]
els = [el[1] for el in id_list]
[k for k,v in {i:els.count(i) for i in els }.items() if v > 1]
['animal']
Kr
How do i filter the following dictionary based on the condition that the ID has to contain three or more timestamps?
dict={10009: {196962305: [Timestamp('2019-12-27 03:06:50')]},
10051: {2854032: [Timestamp('2019-12-27 19:16:11')],
48600461: [Timestamp('2019-12-29 01:56:19')]},
10061: {62464559: [Timestamp('2019-12-31 02:58:48'), Timestamp('2019-12-30 21:35:15'), Timestamp('2019-12-28 09:27:55'), [Timestamp('2019-12-28 12:05:32')]}}
Desired output:
new_dict={10061: {62464559: [Timestamp('2019-12-31 02:58:48'), Timestamp('2019-12-30 21:35:15'), Timestamp('2019-12-28 09:27:55'), [Timestamp('2019-12-28 12:05:32')]}}
Try this:
It will work if the inner dictionary has only one key
res = {k: v for k, v in d.items() if len(list(v.values())[0]) > 2}
print(res)
Output:
{10061: {62464559: [Timestamp('2019-12-31 02:58:48'), Timestamp('2019-12-30 21:35:15'), Timestamp('2019-12-28 09:27:55'), [Timestamp('2019-12-28 12:05:32')]]}}
For example, I have:
dict1 = {"name":"Cristian","surname":"Rossi","nationality":"Italy","color":"red"}
dict2 = {"country":"Italy","loc":"Milan","other":"red","car":"ford"}
dictionaries is large, some thousands elements.
In this example, the values in both dictionaries are Italy and red. So, I would this result
dict3 = {"nationality":"country","color":"other"}
It may be easier to convert the dictionaries into sets?
Thanks!
Get a set of the common values in both dictionaries. Then get the keys for those values and build a dictionary.
dict1 = {"name":"Cristian","surname":"Rossi","nationality":"Italy","color":"red"}
dict2 = {"country":"Italy","loc":"Milan","other":"red","car":"ford"}
common = set(dict1.values()) & set(dict2.values())
keys1 = [k for k,v in dict1.items() if v in common]
keys2 = [k for k,v in dict2.items() if v in common]
d = {k1:k2 for k1,k2 in zip(keys1, keys2)}
print(d)
Output:
{'nationality': 'country', 'color': 'other'}
Here is one approach which first inverts the dicts and then looks at an intersection of the values. Given that intersection of values it then builds a final result with all of the keys that each value mapped to in the original dicts. Assumes Python 3.
d1 = {"name":"Cristian","surname":"Rossi","nationality":"Italy","color":"red"}
d2 = {"country":"Italy","loc":"Milan","other":"red","car":"ford"}
def inv_dict(d):
inv = {}
for k, v in d.items():
inv.setdefault(v, []).append(k)
return inv
id1 = inv_dict(d1)
id2 = inv_dict(d2)
result = {v:id1[v] + id2[v] for v in id1.keys() & id2.keys()}
print(result)
# {'Italy': ['nationality', 'country'], 'red': ['color', 'other']}
The output is slightly different than what you specified, but it's unclear how your example output would work if the same value appeared in multiple keys in one or both dicts.
I have a dictionary:
d = {1:[9,9,9],2:[8,8,8],3:[7,7,7]}
and a list of keys :
newkeylist = [4,2,3]
Now i want check the keys in the dict with the content in the list. If they are different i want to replace the key in the dict with the one in the list.
for i in range(len(newkeylist)):
if d.key()[i] != newkeylist[i]:
d.key()[i] = newkeylist[i]
try something like this
d = {1:[9,9,9],2:[8,8,8],3:[7,7,7]}
newkeylist = [4,2,3]
d_copy = d.copy()
for i, (k, v) in enumerate(d_copy.items()):
if k != newkeylist[i]:
d[newkeylist[i]] = v
del d[k]
but as #jonrsharpe said, it's not an ordered dict: the output is random
I have two separate Python List that have common key names in their respective dictionary. The second list called recordList has multiple dictionaries with the same key name that I want to append the first list clientList. Here are examples lists:
clientList = [{'client1': ['c1','f1']}, {'client2': ['c2','f2']}]
recordList = [{'client1': {'rec_1':['t1','s1']}}, {'client1': {'rec_2':['t2','s2']}}]
So the end result would be something like this so the records are now in a new list of multiple dictionaries within the clientList.
clientList = [{'client1': [['c1','f1'], [{'rec_1':['t1','s1']},{'rec_2':['t2','s2']}]]}, {'client2': [['c2','f2']]}]
Seems simple enough but I'm struggling to find a way to iterate both of these dictionaries using variables to find where they match.
When you are sure, that the key names are equal in both dictionaries:
clientlist = dict([(k, [clientList[k], recordlist[k]]) for k in clientList])
like here:
>>> a = {1:1,2:2,3:3}
>>> b = {1:11,2:12,3:13}
>>> c = dict([(k,[a[k],b[k]]) for k in a])
>>> c
{1: [1, 11], 2: [2, 12], 3: [3, 13]}
Assuming you want a list of values that correspond to each key in the two lists, try this as a start:
from pprint import pprint
clientList = [{'client1': ['c1','f1']}, {'client2': ['c2','f2']}]
recordList = [{'client1': {'rec_1':['t1','s1']}}, {'client1': {'rec_2':['t2','s2']}}]
clientList.extend(recordList)
outputList = {}
for rec in clientList:
k = rec.keys()[0]
v = rec.values()[0]
if k in outputList:
outputList[k].append(v)
else:
outputList[k] = [v,]
pprint(outputList)
It will produce this:
{'client1': [['c1', 'f1'], {'rec_1': ['t1', 's1']}, {'rec_2': ['t2', 's2']}],
'client2': [['c2', 'f2']]}
This could work but I am not sure I understand the rules of your data structure.
# join all the dicts for better lookup and update
clientDict = {}
for d in clientList:
for k, v in d.items():
clientDict[k] = clientDict.get(k, []) + v
recordDict = {}
for d in recordList:
for k, v in d.items():
recordDict[k] = recordDict.get(k, []) + [v]
for k, v in recordDict.items():
clientDict[k] = [clientDict[k]] + v
# I don't know why you need a list of one-key dicts but here it is
clientList = [dict([(k, v)]) for k, v in clientDict.items()]
With the sample data you provided this gives the result you wanted, hope it helps.