【问题标题】:How to add a column with values of a dictionary in Python如何在 Python 中添加具有字典值的列
【发布时间】:2020-12-04 19:03:00
【问题描述】:

我正在尝试添加一个包含字典值的列。向您展示虚拟数据会很容易。

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]]})

【问题讨论】:

标签: python pandas dataframe dictionary


【解决方案1】:

这是你想要的吗?

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

df['new_column'] = df['id'].map(dictionary)

【讨论】:

  • 我更新了这个答案,在分配新数据之前将df 的索引设置为'id' 值。
  • 我注意到在数据框中,同一个id出现了多次。你的代码可以吗?
  • 我认为它会起作用,但索引不应有重复项,因此在这种情况下可能不建议这样做。一个更好的选择是使用df.map,如this answer 中所述。像这样:df['new_column'] = df['id'].map(dictionary).
【解决方案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]

new_column 现在是 [[5, 8, 6, 3], [1, 2], [], [], [8, 6, 2]],您可以将它传递给 pd.DataFrame(...) 的最后一个参数

【讨论】:

  • 有一种更好的方法可以从现有字典中创建默认字典:default_dictionary = defaultdict(list, **dictionary)。最后,只分配列也是有意义的,就像比尔在他的回答中所做的那样
  • 哦,这确实好多了。谢谢
【解决方案3】:
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]}

然后只需创建一个包含您想要的值的列表并将它们添加到您的数据框

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2016-12-21
    • 1970-01-01
    • 2021-12-06
    • 2018-09-28
    相关资源
    最近更新 更多