【问题标题】:Replacing non-null values with column names用列名替换非空值
【发布时间】:2018-01-31 04:15:53
【问题描述】:

给定以下数据框:

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

我想用列名替换所有非空值。

想要的结果:

    a   b
0   a   NaN
1   a   b
2   a   b

实际上,我有很多专栏。

提前致谢!

更新以从 root 回答: 要在列的子集上执行此操作:

d.loc[:,d.columns[3:]] = np.where(d.loc[:,d.columns[3:]].notnull(), d.loc[:,d.columns[3:]].columns, d.loc[:,d.columns[3:]])

【问题讨论】:

  • 如果您想将我的方法用于子集,则不需要loc。查看我的编辑。

标签: python pandas dataframe replace


【解决方案1】:

我可以想到使用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

【讨论】:

  • 既好答案又难选择。顺便说一句,如果我需要对一部分列执行此操作怎么办?
  • @DanceParty2 您可以使用df.loc 进行基于切片的索引,并对切片执行操作。
  • 嗨 @cᴏʟᴅsᴘᴇᴇᴅ d.apply(lambda x: np.where(x.isnull(),x,x.name)) 和 transform 有什么不同:)
  • @Wen 我认为df.transform 是矢量化的...?不是100%确定。我知道apply 很慢。
  • @COLDSPEED 可以。谢谢!
【解决方案2】:

使用numpy.wherenotnull

d[:] = np.where(d.notnull(), d.columns, d)

结果输出:

   a    b
0  a  NaN
1  a    b
2  a    b

编辑

要选择特定的列:

cols = d.columns[3:]  # or whatever Index/list-like of column names
d[cols] = np.where(d[cols].notnull(), cols, d[cols])

【讨论】:

    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 2021-03-05
    • 2015-06-26
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    相关资源
    最近更新 更多