[英]Assign multiple columns different values based on conditions in Panda dataframe
I have dataframe where new columns need to be added based on existing column values conditions and I am looking for an efficient way of doing.我有数据框,需要根据现有列值条件添加新列,我正在寻找一种有效的方法。 For Ex:
例如:
df = pd.DataFrame({'a':[1,2,3],
'b':['x','y','x'],
's':['proda','prodb','prodc'],
'r':['oz1','0z2','oz3']})
I need to create 2 new columns ['c','d'] based on following conditions我需要根据以下条件创建 2 个新列 ['c','d']
If df['b'] == 'x':
df['c'] = df['s']
df['d'] = df['r']
elif df[b'] == 'y':
#assign different values to c, d columns
We can use numpy where and apply conditions on new column like我们可以使用 numpy where 并在新列上应用条件,例如
df['c] = ny.where(condition, value)
df['d'] = ny.where(condition, value)
But I am looking if there is a way to do this in a single statement or without using for loop or multiple numpy or panda apply.但我正在寻找是否有一种方法可以在单个语句中执行此操作,或者不使用 for 循环或多个 numpy 或 panda apply。
The exact output is unclear, but you can use numpy.where
with 2D data.确切的输出尚不清楚,但您可以将
numpy.where
与 2D 数据一起使用。
For example:例如:
cols = ['c', 'd']
df[cols] = np.where(df['b'].eq('x').to_numpy()[:,None],
df[['s', 'r']], np.nan)
output:输出:
a b s r c d
0 1 x proda oz1 proda oz1
1 2 y prodb 0z2 NaN NaN
2 3 x prodc oz3 prodc oz3
If you want multiple conditions, use np.select
:如果您想要多个条件,请使用
np.select
:
cols = ['c', 'd']
df[cols] = np.select([df['b'].eq('x').to_numpy()[:,None],
df['b'].eq('y').to_numpy()[:,None]
],
[df[['s', 'r']],
df[['r', 'a']]
], np.nan)
it is however easier here to use a loop for the conditions if you have many:但是,如果您有很多条件,则在这里使用循环更容易:
cols = ['c', 'd']
df[cols] = np.select([df['b'].eq(c).to_numpy()[:,None] for c in ['x', 'y']],
[df[repl] for repl in (['s', 'r'], ['r', 'a'])],
np.nan)
output:输出:
a b s r c d
0 1 x proda oz1 proda oz1
1 2 y prodb 0z2 0z2 2
2 3 x prodc oz3 prodc oz3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.