创建下面提到的同一列的更好的方法是什么?
col_new = []
for r1 in df['col_A']:
if r1==1:
for r2 in df['col_B']:
if r2!='None':
col_new.append('col_new')
df['col_new'] = col_new
我的数据帧很大(120k * 22),运行上面的代码使笔记本挂起。有没有一种更快,更有效的方法来创建此列,该列表示col_A为1时col_B的所有非空值。
答案 0 :(得分:0)
我认为需要创建布尔掩码,然后通过DataFrame.loc
附加值:
mask = (df['col_A'] == 1) & (df['col_B']!='None')
#if None is not string
#mask = (df['col_A'] == 1) & (df['col_B'].notnull())
df.loc[mask, 'col_new'] = 'col_new'
示例:
列中是字符串None
:
df = pd.DataFrame({
'col_A': [1,1,2,1],
'col_B': ['a','None','None','a']
})
print (df)
col_A col_B
0 1 a
1 1 None
2 2 None
3 1 a
mask = (df['col_A'] == 1) & (df['col_B']!='None')
df.loc[mask, 'col_new'] = 'val'
print (df)
col_A col_B col_new
0 1 a val
1 1 None NaN
2 2 None NaN
3 1 a val
在列not strings None
s中,然后使用Series.notna
:
df = pd.DataFrame({
'col_A': [1,1,2,1],
'col_B': ['a',None,None,'a']
})
print (df)
col_A col_B
0 1 a
1 1 None
2 2 None
3 1 a
mask = (df['col_A'] == 1) & (df['col_B'].notna())
#oldier pandas versions
#mask = (df['col_A'] == 1) & (df['col_B'].notnull())
df.loc[mask, 'col_new'] = 'val'
print (df)
col_A col_B col_new
0 1 a val
1 1 None NaN
2 2 None NaN
3 1 a val
如果还想使用if-else
语句numpy.where
真的很有帮助:
df['col_new'] = np.where(mask, 'val', 'another_val')
print (df)
col_A col_B col_new
0 1 a val
1 1 None another_val
2 2 None another_val
3 1 a val