我遵循了以下程序:In Python, how do I convert all of the items in a list to floats?因为我的 Dataframe 的每一列都是 list
,但我选择将所有值更改为 strings
而不是 floats
。
df = [str(i) for i in df]
但这失败了。
它只是删除了除第一行列名之外的所有数据。
然后,尝试 df = [str(i) for i in df.values]
导致将整个 Dataframe 变成一个大列表,但这会把数据搞得一团糟,无法满足我的脚本的目标,即将 Dataframe 导出到我的 Oracle 表。
有没有办法将我的 Dataframe 中所有非字符串的项目转换为字符串?
最佳答案
你可以使用这个:
df = df.astype(str)
出于好奇,我决定看看公认的解决方案与我的解决方案在效率上是否存在差异。
结果如下:
示例 df:
df = pd.DataFrame([list(range(1000))], index=[0])
测试df.astype
:
%timeit df.astype(str)
>> 100 loops, best of 3: 2.18 ms per loop
测试df.applymap
:
%timeit df.applymap(str)
1 loops, best of 3: 245 ms per loop
看起来 df.astype
快了很多:)
关于Python - 将数据框中的所有项目转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42676982/