我有一个数据框
data = {'A':['a','a',3,3,'c','c'],'B': [0, .5, 101, 105, 2000, 2500]}
df = pd.DataFrame(data, columns = ['A','B'])
和字典
d = {'a':['a',3,'c'],'b':[5,200,3000],'c':[1,2,3]}
我想使用d['a']
与df['A']
进行比较,如果相等,则将d['b']
到df['B']
的值添加到新列df['C']
中结果将是
data2 = {'A':['a','a','b','b','c','c'],'B': [0, .5, 101, 105, 2000, 2500],'C':[5,5.5,301,305,5000,5500]}
df2 = pd.DataFrame(data2, columns = ['A','B','C'])
答案 0 :(得分:1)
另一种方法是构造一个普通地图:
import pandas as pd
data = {'A':['a','a',3,3,'c','c','d'],'B': [0, .5, 101, 105, 2000, 2500, 3000]}
df = pd.DataFrame(data, columns = ['A','B'])
m = dict(zip(d['a'],d['b']))
df['C'] = df['B'] + df['A'].map(m).fillna(0) # Fillna to avoid Not A Number (NaN
print(df)
返回:
A B C
0 a 0.0 5.0
1 a 0.5 5.5
2 3 101.0 301.0
3 3 105.0 305.0
4 c 2000.0 5000.0
5 c 2500.0 5500.0
6 d 3000.0 3000.0