我正在尝试添加一个列,其中包含字典中的值。这将是很容易向您展示虚拟数据。
df = pd.DataFrame({'id':[1,2,3,2,5], 'grade':[5,2,2,1,3]})
dictionary = {'1':[5,8,6,3], '2':[1,2], '5':[8,6,2]}注意,并非每个id都在字典和作为列表的值中。我希望在df中找到与字典中的键匹配的行,并在一列中添加列表。因此,所需的输出如下所示:
output = pd.DataFrame({'id':[1,2,3,2,5], 'grade':[5,2,2,1,3], 'new_column':[[5,8,6,3],[1,2],[],[1,2],[8,6,2]]})发布于 2020-08-14 21:57:18
这是你想要的吗?
df = df.set_index('id')
dictionary = {1:[5,8,6,3], 2:[1,2], 5:[8,6,2]}
df['new_column'] = pd.Series(dictionary)注意:字典的键必须与数据帧的索引相同类型(int)。
>>> print(df)
gender new_column
id
1 0 [5, 8, 6, 3]
2 0 [1, 2]
3 1 NaN
4 1 NaN
5 1 [8, 6, 2]更新:
如果'id'列包含重复项(请参见下面的注释),则提供更好的解决方案:
df['new_column'] = df['id'].map(dictionary)发布于 2020-08-14 22:01:55
import pandas as pd
df = pd.DataFrame({'id':[1,2,3,4,5], 'gender':[0,0,1,1,1]})
dictionary = {'1':[5,8,6,3], '2':[1,2], '5':[8,6,2]}然后创建一个包含您想要的值的列表,并将它们添加到您的dataframe中。
newValues = [ dictionary.get(str(val),[]) for val in df['id'].values]
df['new_column'] = newValues
>>> print(df)
gender new_column
id
1 0 [5, 8, 6, 3]
2 0 [1, 2]
3 1 []
4 1 []
5 1 [8, 6, 2]发布于 2020-08-14 22:06:42
您可以使用默认值为[]的特殊字典来构造列。
from collections import defaultdict
default_dictionary = defaultdict(list)
id = [1,2,3,4,5]
dictionary = {'1':[5,8,6,3], '2':[1,2], '5':[8,6,2]}
for n in dictionary:
default_dictionary[n] = dictionary[n]
new_column = [default_dictionary[str(n)] for n in id]new_column现在是[[5, 8, 6, 3], [1, 2], [], [], [8, 6, 2]],您可以将它传递到pd.DataFrame(...)的最后一个参数
https://stackoverflow.com/questions/63420426
复制相似问题