鉴于此数据:
data = {'C1_IND' : [1,1,0,0,1],
'C1_PRICE' : [55,84,0,0,103],
'P1_IND' : [1,0,0,1,1],
'P1_PRICE' : [72,0,0,33,95]}
df = pd.DataFrame(data)
如何在同一数据框中创建变量:
max(C1_IND*C1_PRICE,P1_IND*P1_PRICE)
此外,如果该数据中存在空值,是否会出现任何问题?
答案 0 :(得分:3)
我认为您可以按filter
选择列,然后按prod
选择多个列。最后一次申请max
:
a = df.filter(like='C1').prod(1)
b = df.filter(like='P1').prod(1)
df['max'] = pd.DataFrame({'a':a,'b':b}).max(1)
print (df)
C1_IND C1_PRICE P1_IND P1_PRICE max
0 1 55 1 72 72
1 1 84 0 0 84
2 0 0 0 0 0
3 0 0 1 33 33
4 1 103 1 95 103
或者:
df['a'] = df.filter(like='C1').prod(1)
df['b'] = df.filter(like='P1').prod(1)
df['max'] = df[['a','b']].max(1)
df = df.drop(['a','b'], axis=1)
print (df)
C1_IND C1_PRICE P1_IND P1_PRICE max
0 1 55 1 72 72
1 1 84 0 0 84
2 0 0 0 0 0
3 0 0 1 33 33
4 1 103 1 95 103
它也适用于NaN
,但将参数skipna=False
添加到prod
:
data = {'C1_IND' : [1,1,0,0,1],
'C1_PRICE' : [55,84,0,0,8],
'P1_IND' : [1,0,0,1,10],
'P1_PRICE' : [72,0,0,33,np.nan]}
df = pd.DataFrame(data)
print (df)
C1_IND C1_PRICE P1_IND P1_PRICE
0 1 55 1 72.0
1 1 84 0 0.0
2 0 0 0 0.0
3 0 0 1 33.0
4 1 8 10 NaN
a = df.filter(like='C1').prod(1, skipna=False)
b = df.filter(like='P1').prod(1, skipna=False)
print (pd.DataFrame({'a':a,'b':b}))
a b
0 55 72.0
1 84 0.0
2 0 0.0
3 0 33.0
4 8 NaN
df['max'] = pd.DataFrame({'a':a,'b':b}).max(1)
print (df)
C1_IND C1_PRICE P1_IND P1_PRICE max
0 1 55 1 72.0 72.0
1 1 84 0 0.0 84.0
2 0 0 0 0.0 0.0
3 0 0 1 33.0 33.0
4 1 8 10 NaN 8.0