如何根据两个或多个其他变量创建pandas dataframe变量/列?

时间:2016-08-16 15:08:33

标签: python pandas dataframe

我有一个pandas数据帧,例如:

Col1 Col2
A     1 
B     2
C     3

我理解如何基于Col2的值来创建Col3:

df['Col3'] = (df['Col2'] <= 1).astype(int)

但是......如果新列基于两个变量,如(伪代码):

if Col2=1 and Col3=1 then Col4='X'
else if Col2=1 and Col3=2 then Col4='Y'
else Col4='Z'

如何实现?非常感谢

2 个答案:

答案 0 :(得分:1)

您可以尝试加倍numpy.where

df['Col4'] = np.where((df['Col2'] == 1) & (df['Col3'] == 1), 'X', 
             np.where((df['Col2'] == 1) & (df['Col3'] == 2), 'Y', 'Z'))

样品:

import pandas as pd

df = pd.DataFrame({'Col2': {0: 1, 1: 1, 2: 3}, 
                   'Col1': {0: 'A', 1: 'B', 2: 'C'}, 
                   'Col3': {0: 1, 1: 2, 2: 4}})
print (df)

  Col1  Col2  Col3
0    A     1     1
1    B     1     2
2    C     3     4

df['Col4'] = np.where( (df['Col2'] == 1) & (df['Col3'] == 1), 'X', 
             np.where((df['Col2'] == 1) & (df['Col3'] == 2), 'Y', 'Z'))

print (df)
  Col1  Col2  Col3 Col4
0    A     1     1    X
1    B     1     2    Y
2    C     3     4    Z

使用locfillna填充NaN所有其他值的另一个解决方案:

df.loc[ (df['Col2'] == 1) & (df['Col3'] == 1) , 'Col4'] =  'X'
df.loc[ (df['Col2'] == 1) & (df['Col3'] == 2) , 'Col4'] =  'Y'
df['Col4'] = df['Col4'].fillna('Z')

print (df)
  Col1  Col2  Col3 Col4
0    A     1     1    X
1    B     1     2    Y
2    C     3     4    Z

答案 1 :(得分:0)

您可以使用最终else值初始化列(例如Z),然后检查每个条件:

df['Col4'] = 'Z'
df.loc[(df.Col1 == 1) & (df.Col3 == 1), 'Col4'] = 'X'
df.loc[(df.Col2 == 1) & (df.Col3 == 2), 'Col4'] = 'Y'