Python - 将数据框中的所有项目转换为字符串

标签 python string pandas dataframe

我遵循了以下程序: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/

相关文章:

python - Django 不允许的主机

javascript - 为什么 '❌' [0] === '❌' 但 '✔️' [0] !== '✔️' ?

c# - String.IsNullOrEmpty(myString) 与 myString != null

java - replaceAll 悬挂元字符

python - 获取 QListWidget 中选定复选框的索引

python - (Python) 类型错误 : 'float' object is not subscriptable

python - 如何在 ipython-notebook 中获取 sympy 表达式的 latex 表?

python - 如何使用 Python 将查询导出到 Excel?

python - 两列两行滚动的 Pandas Dataframe

python - 使用 Python 的 odesk API POST 作业