用列名替换非空值 [英] Replacing non-null values with column names
本文介绍了用列名替换非空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下数据框:
import pandas as pd
d = pd.DataFrame({'a':[1,2,3],'b':[np.nan,5,6]})
d
a b
0 1 NaN
1 2 5.0
2 3 6.0
我想用列名替换所有非空值.
I would like to replace all non-null values with the column name.
所需结果:
a b
0 a NaN
1 a b
2 a b
实际上,我有很多列.
提前谢谢!
更新为从根目录回答: 要在一部分列上执行此操作,请执行以下操作:
Update to answer from root: To perform this on a subset of columns:
d.loc[:,d.columns[3:]] = np.where(d.loc[:,d.columns[3:]].notnull(), d.loc[:,d.columns[3:]].columns, d.loc[:,d.columns[3:]])
推荐答案
我可以想到使用apply/transform
的一种可能性:
I can think of one possibility using apply/transform
:
In [1610]: d.transform(lambda x: np.where(x.isnull(), x, x.name))
Out[1610]:
a b
0 a nan
1 a b
2 a b
您还可以使用df.where
:
In [1627]: d.where(d.isnull(), d.columns.values.repeat(len(d)).reshape(d.shape))
Out[1627]:
a b
0 a NaN
1 a b
2 b b
这篇关于用列名替换非空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文