Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中添加包含字典值的列_Python_Pandas_Dataframe_Dictionary - Fatal编程技术网

如何在Python中添加包含字典值的列

如何在Python中添加包含字典值的列,python,pandas,dataframe,dictionary,Python,Pandas,Dataframe,Dictionary,我试图添加一个包含字典中值的列。向您显示虚拟数据将很容易 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],

我试图添加一个包含字典中值的列。向您显示虚拟数据将很容易

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]]})
这是你想要的吗

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'
列包含重复项,则是更好的解决方案(请参见下面的注释):

然后创建一个包含所需值的列表,并将它们添加到数据帧中

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]

您可以使用默认值为
[]
的特殊词典构造列

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]

新的_列现在是
[[5,8,6,3],[1,2],[],[8,6,2]
,您可以将它传递到
pd.DataFrame(…)

的最后一个参数,在分配新数据之前,我更新了这个答案,将
df
的索引设置为
'id'
值。我注意到在数据框中,相同的id多次出现。你的代码可以这样做吗?我认为它可以工作,但是索引不应该有重复项,所以在这种情况下,它可能是不可取的。更好的选择是使用
df.map
,如中所述。类似这样:
df['new\u column']=df['id'].map(dictionary)
。有一种更好的方法可以从现有字典生成defaultdict:
default\u dictionary=defaultdict(list,**dictionary)
。最后,像比尔在他的回答中那样,分配专栏也是有意义的。这确实好得多。谢谢B.t.w.:在发布之前,一定要检查是否有人问过问题。如果你用谷歌搜索你的问题,你会发现有很多重复的问题。这能回答你的问题吗?
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]
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]