簡體   English   中英

用列名替換非空值

[英]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

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

期望的結果:

    a   b
0   a   NaN
1   a   b
2   a   b

實際上,我有很多專欄。

提前致謝!

更新以從根回答:要對列的子集執行此操作:

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

使用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])

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM