我有一个数据框:
a-line abstract ... zippered
0 0 ... 0
0 1 ... 0
0 0 ... 1
其中单元格的值为1
,我需要将其替换为标题名称。
[df.dtypes
返回Length: 1000, dtype: object
我尝试过df.apply(lambda x: x.astype(object).replace(1, x.name))
但是得到TypeError: Invalid "to_replace" type: 'int'
其他尝试:
df.apply(lambda x: x.astype(object).replace(str(1), x.name))
== TypeError: Invalid "to_replace" type: 'str'
df.apply(lambda x: x.astype(str).replace(str(1), x.name))
== Invalid "to_replace" type: 'str'
循环浏览列并替换为列的名称。
for col in df:
df[col]=df[col].replace(1, df[col].name)
或者,根据您的方法:
for col in df_new:
df_new[col]=df_new[col].astype(str).apply(lambda x: x.replace('1',df_new[col].name))