【发布时间】:2018-02-06 19:20:21
【问题描述】:
我有一个包含 True 和 False 值的 DataFrame。
A B C D 0 假 真 真 假 1 假 假 真 假 2 真 真 假 假我想用列名填充真值,用 0 填充假值。我该怎么做?
即得到结果为
A B C D 0 0 B C 0 1 0 0 C 0 2 A B 0 0【问题讨论】:
我有一个包含 True 和 False 值的 DataFrame。
A B C D 0 假 真 真 假 1 假 假 真 假 2 真 真 假 假我想用列名填充真值,用 0 填充假值。我该怎么做?
即得到结果为
A B C D 0 0 B C 0 1 0 0 C 0 2 A B 0 0【问题讨论】:
首先将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
感谢John Galt对新版pandas的改进0.21.x:
df = df.astype(int).mask(df, df.columns, axis=1)
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
【讨论】:
df.astype(int).mask(df, df.columns, axis=1) 我应该猜吗?
ValueError: other must be the same shape as self when an ndarray
df.astype(int).where(~df, df.columns.to_series(), axis=1) 也可以。
0.20.3,python 3.5,windows 7