[英]How to fill true values of a dataframe with column names?
I have a DataFrame with True and False values.我有一个带有 True 和 False 值的 DataFrame。
A B C D 0 False True True False 1 False False True False 2 True True False False
I want to fill the true values with column names and false values with 0. How can I do that?我想用列名填充真值,用 0 填充假值。我该怎么做?
ie To get the result as即得到结果为
A B C D 0 0 B C 0 1 0 0 C 0 2 A B 0 0
First replace booelan
to int
and then use mask
or where
with inverting mask by ~
: 首先更换booelan
来int
和再使用mask
或where
通过反向掩码~
:
df = df.astype(int).mask(df, df.columns.to_series(), axis=1)
print (df)
A B C D
0 0 B C 0
1 0 0 C 0
2 A B 0 0
df = df.astype(int).where(~df, df.columns.to_series(), axis=1)
print (df)
A B C D
0 0 B C 0
1 0 0 C 0
2 A B 0 0
Thank you John Galt for improvement in new versions of pandas 0.21.x
: 感谢John Galt对新版pandas 0.21.x
:
df = df.astype(int).mask(df, df.columns, axis=1)
numpy
solution: numpy
解决方案:
a = np.tile(df.columns, [len(df.index),1])
print (a)
[['A' 'B' 'C' 'D']
['A' 'B' 'C' 'D']
['A' 'B' 'C' 'D']]
df = pd.DataFrame(np.where(df.astype(int), a, 0), columns=df.columns, index = df.index)
print (df)
A B C D
0 0 B C 0
1 0 0 C 0
2 A B 0 0
pandas 1.5.2 pandas 1.5.2
df = df.mask(df.astype(bool), df.columns.to_series(), axis=1)
not astype(int)
but astype(bool) or astype('bool')
不是astype(int)
而是astype(bool) or astype('bool')
Otherwise ValueError: Boolean array expected for the condition, not uint8否则ValueError:条件应为 Boolean 数组,而不是 uint8
can't remove .to_series()
无法删除.to_series()
Otherwise ValueError: other must be the same shape as self when an ndarray否则ValueError: other must be the same shape as self when an ndarray
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.