Python 如何使用基于2列的多个条件在pandas中创建新列?
我有两个字典,我需要根据几个条件创建列Python 如何使用基于2列的多个条件在pandas中创建新列?,python,pandas,dataframe,dictionary,conditional-statements,Python,Pandas,Dataframe,Dictionary,Conditional Statements,我有两个字典,我需要根据几个条件创建列 dict1 = {'100': BMW, '200': Audi, '300': 'VW'} dict2 = {'100': Mercedes, '200': Nissan, '300': 'Renault'} df: 实际上,我想在类为1时使用dict1,在类为2时使用dict2 所需的输出如下: class Code Car 1 200 Audi
dict1 = {'100': BMW, '200': Audi, '300': 'VW'}
dict2 = {'100': Mercedes, '200': Nissan, '300': 'Renault'}
df:
实际上,我想在类为1时使用dict1,在类为2时使用dict2
所需的输出如下:
class Code Car
1 200 Audi
1 300 VW
2 300 Renault
1 100 BMW
2 100 Mercedes
如果没有条件,我可以使用.map,但我不确定现在使用什么:
df['Car'] = df['Code'].map(dict1)
如果只是两个字典/类:
# note that your dictionary has string key
df['Code'] = df.Code.astype(str)
df['car'] = np.where(df['class']==1,
df['Code'].map(dict1),
df['Code'].map(dict2) )
输出:
class Code Car
0 1 200 Audi
1 1 300 VW
2 2 300 Renault
3 1 100 BMW
4 2 100 Mercedes
我用下面的代码进行了测试
import pandas as pd
dict1 = {'100': 'BMW', '200': 'Audi', '300': 'VW'}
dict2 = {'100': 'Mercedes', '200': 'Nissan', '300': 'Renault'}
df = pd.DataFrame({'Class':[1,1,2,1],'Code':['200','300','300','100']})
def f(row):
if row['Class'] == 1:
val = dict1[row['Code']]
elif row['Class'] ==2:
val = dict2[row['Code']]
else:
val = dict2[row['Code']]
return val
df['Car']= df.apply(f,axis=1)
print(df)
它打印
Class Code Car
0 1 200 Audi
1 1 300 VW
2 2 300 Renault
3 1 100 BMW
谢谢:)如果我有两本以上的词典,那么写这三本词典的最佳方式是什么?有没有3本词典的想法?如何使用
np.选择?如何使用np.选择?@jezrael你能帮我吗?
Class Code Car
0 1 200 Audi
1 1 300 VW
2 2 300 Renault
3 1 100 BMW