我知道这个问题已经被问过几次了,但是我似乎无法使其正常工作。我想将等于特定值的所有行值复制到单独的列。使用下面的df
,当np.nan
位于Member
中时,我想跨np.nan
复制到Group
。
import pandas as pd
import numpy as np
df = pd.DataFrame({
'Member' : ['C1','C2','C3','C4','C5',np.nan,np.nan],
'Min' : [5,5,5,5,5,5,5],
'Max' : [10,10,10,10,10,10,10],
'Group' : [26,26,26,26,26,26,26],
})
# Attempt 1
df['Group'] = np.where(df['Member'] == np.nan, df['Group'], df['Member'])
# Attempt 2
df['Group'] = df.apply(lambda x: x['Member'] if x['Group'] == np.nan else x['Group'], axis=1)
这两种尝试均无效。预期的输出是:
Member Min Max Group
0 C1 5 10 26
1 C2 5 10 26
2 C3 5 10 26
3 C4 5 10 26
4 C5 5 10 26
5 NaN 5 10 Nan
6 NaN 5 10 Nan
答案 0 :(得分:2)
代码具有特殊功能的解决方案,用于Series.isna
测试缺失值,并将Member
与Group
中的np.where
列交换:
df['Group'] = np.where(df['Member'].isna(), df['Member'], df['Group'])
#alternative with notna
#df['Group'] = np.where(df['Member'].notna(), df['Group'], df['Member'])
#alternative with loc
#df.loc[df['Member'].isna(), 'Group'] = df['Member']
print (df)
Member Min Max Group
0 C1 5 10 26
1 C2 5 10 26
2 C3 5 10 26
3 C4 5 10 26
4 C5 5 10 26
5 NaN 5 10 NaN
6 NaN 5 10 NaN