首页 > 解决方案 > 使用字典从现有的列中生成新列

问题描述

问题的本质是“在DataFrame中创建一个新列”,基于现有列'user_id'和字典{dict},它作为字典'user_id'列的值的键和字典的值类型。

我有以下 DataFrame df。

    df = pd.DataFrame({"user_id" : [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5], 
                  "value" : [0, 100, 50, 0, 25, 50, 100, 0, 7, 8, 20]})
    print(df)
     | user_id | value 
     _________________

0    |     1   |    0  
1    |     2   |  100  
2    |     2   |   50  
3    |     3   |    0  
4    |     3   |   25  
5    |     3   |   50  
6    |     4   |  100  
7    |     4   |    0  
8    |     4   |    7  
9    |     4   |    8  
10   |     5   |   20  

另外,我有一本字典,它是

dict = {1 : 'type_a', 2: 'type_b', 3: 'type_a', 4: 'type_b', 5: 'type_a'}

我的想法是在我的 DataFrame df 中创建第三列,称为关税,所以如果我有一个 user_id 3,DataFrame 中的所有行都会有 a 类型的关税。

我找到了一种解决方案,但我不太明白它是如何实现的。

df['tariffs'] = df.apply(lambda x: dict[x.user_id], axis=1)
print(df)
     | user_id | value |
     _________________________

0    |     1   |    0  |type_a
1    |     2   |  100  |type_b
2    |     2   |   50  |type_b
3    |     3   |    0  |type_a
4    |     3   |   25  |type_a
5    |     3   |   50  |type_a
6    |     4   |  100  |type_b
7    |     4   |    0  |type_b
8    |     4   |    7  |type_b
9    |     4   |    8  |type_b
10   |     5   |   20  |type_a

我在这行代码之后得到的结果正是我想要的

特别是我不明白这部分dict[x.user_id] 问题是我使用的方法是否有任何替代方法。而背后的逻辑是什么dict[x.user_id]。提前致谢

标签: pythonpandasdictionary

解决方案


像这样写得更清楚:

df['tariffs'] = df.apply(lambda row: dict[row['user_id']], axis=1)

lambda函数应用于数据帧的每一行(因为axis = 1),结果被连接并影响到新列df['tariffs']


推荐阅读