我有一些专栏 ['a', 'b', 'c', etc.]
( a
和 c
是 float64
而 b
是 object
)
我想将所有列转换为字符串并保留 nan
s。
尝试使用 df[['a', 'b', 'c']] == df[['a', 'b', 'c']].astype(str)
但这为 float64
留下了空白列。
目前我正在一一处理以下内容:
df['a'] = df['a'].apply(str)
df['a'] = df['a'].replace('nan', np.nan)
是最好的使用方式
.astype(str)
然后替换 ''
与 np.nan
?附带问题:.astype(str)
之间有区别吗?和 .apply(str)
?样本输入: (数据类型:a=float64,b=object,c=float64)
a, b, c, etc.
23, 'a42', 142, etc.
51, '3', 12, etc.
NaN, NaN, NaN, etc.
24, 'a1', NaN, etc.
所需输出: (dtypes: a=object, b=object, c=object)
a, b, c, etc.
'23', 'a42', '142', etc.
'51', 'a3', '12', etc.
NaN, NaN, NaN, etc.
'24', 'a1', NaN, etc.
最佳答案
这为您提供了列名列表
lst = list(df)
这会将所有列转换为字符串类型
df[lst] = df[lst].astype(str)
关于string - Pandas :将多列转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37035182/