只有在数据框的特定列中不为null时,最好的处理方式是什么?
我的原始代码:
for i in columns_to_process:
df[i] = df[i].astype(str) + '!'
#columns_to_process is a list of selected df column name strings
我意识到这会将空值转换为nan!
,但我只想保持它们为空。
我已经研究过使用.apply()
和一个lambda
函数,但是根据Pandas: How can I use the apply() function for a single column?,显然当处理单个列时,这是不好的做法。似乎.apply()
更适合更新数据框中的每一列。
然后我遇到了这个问题:replace non Null values in column by 1,并设法提出了可行的解决方案:
for i in columns_to_process:
df.loc[df[i].notnull(), i] = df.loc[df[i].notnull(), i].astype(str) + '!'
我花了很长时间才弄清楚这一点,而且看起来还不太优雅,所以我想知道是否有更好/更蟒蛇的方法来做到这一点?
答案 0 :(得分:2)
IIUC,尝试pandas.DataFrame.where
:
# Sample df
df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two',
'two'],
'bar': ['A', 'B', np.nan, 'A', 'B', 'C'],
'baz': [1, 2, np.nan, 4, 5, 6],
'zoo': ['x', 'y', 'z', 'q', 'w', 't']})
columns_to_process = ['bar', 'baz']
df[columns_to_process] = df[columns_to_process].where(df[columns_to_process].isna(), lambda x: x.astype(str)+'!')
df
输出:
bar baz foo zoo
0 A!! 1.0!! one x
1 B!! 2.0!! one y
2 NaN NaN one z
3 A!! 4.0!! two q
4 B!! 5.0!! two w
5 C!! 6.0!! two t
答案 1 :(得分:1)
将DataFrame.where
与DataFrame.add
一起使用
df.astype(str).add('!').where(df.notnull())
#to fill NaN with the previous null values
#df.astype(str).add('!').where(df.notnull(),df)