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

Python-将数据帧中的所有项转换为字符串,python,string,pandas,dataframe,Python,String,Pandas,Dataframe,我遵循了以下过程:因为我的数据帧的每一列都是列表,但不是浮动,我选择将所有值更改为字符串 df=[str(i)表示df中的i] 但这失败了 它只是删除了除第一行列名之外的所有数据 然后,尝试df=[str(i)for i in df.values]会将整个数据帧更改为一个大列表,但这会将数据弄得太乱,无法满足脚本的目标,即将数据帧导出到Oracle表 有没有办法将我的数据框中所有非字符串的项转换为字符串 您可以使用applymap方法: df = df.applymap(str) 您可以使用以

我遵循了以下过程:因为我的数据帧的每一列都是
列表
,但不是
浮动
,我选择将所有值更改为
字符串

df=[str(i)表示df中的i]

但这失败了

它只是删除了除第一行列名之外的所有数据

然后,尝试
df=[str(i)for i in df.values]
会将整个数据帧更改为一个大列表,但这会将数据弄得太乱,无法满足脚本的目标,即将数据帧导出到Oracle表


有没有办法将我的数据框中所有非字符串的项转换为字符串

您可以使用
applymap
方法:

df = df.applymap(str)
您可以使用以下选项:

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
要快得多:)

这对我很有效:

dt.applymap(lambda x: x[0] if type(x) is list else None)

对于pandas>=1.0,现在有一个专用的字符串数据类型:

您可以使用以下方法将列转换为该字符串数据类型:

这与使用设置“对象”数据类型的
str
不同:

df = df.astype(str)
当您查看数据帧的信息时,可以看到数据类型的差异:

df = pd.DataFrame({
    'zipcode_str': [90210, 90211] ,
    'zipcode_string': [90210, 90211],
})

df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')

df.info()

# you can see that the first column has dtype object
# while the second column has the new dtype string
 #   Column          Non-Null Count  Dtype 
---  ------          --------------  ----- 
 0   zipcode_str     2 non-null      object
 1   zipcode_string  2 non-null      string
dtypes: object(1), string(1)

从文档中:

“string”扩展类型解决了对象数据类型的几个问题 NumPy阵列:

1) 您可能会意外地将字符串和非字符串混合存储在 对象数据类型数组。StringArray只能存储字符串

2) 对象数据类型中断数据类型特定的操作,如 数据帧。选择数据类型()。没有一种明确的方法可以只选择文本 虽然排除了非文本,但仍然是对象数据类型列

3) 读取代码时,对象数据类型数组的内容不太清晰 而不是字符串。


有关熊猫1.0的信息可在此处找到:

它工作得非常完美,修复了我的整个代码。谢谢,托尼,我不知道你的数据框有多大,但看起来aType要快得多。请参阅我的答案:)。请小心将其与nan值一起使用,这会将它们转换为“nan”字符串。如果要将数据帧列表转换为字符串,您将如何执行此操作?list_of_dfs=[df.astype(str)for df in list_of_dfs]这似乎将所有的数据帧放在一个数据帧列表中,虽然它将它们转换为字符串,但实际上并没有将原始dfs转换为字符串。我必须把它们拆开,重新分配给它们原来的df名称。有没有一种简单的方法可以做到这一点呢?这可以用[df_a,df_b,df_c]=[df.astype(str)来表示[df_a,df_b,df_c]],但这不行。list_of_dfs=[df.astype(str)for df in list_of_dfs]啊,我没有真正理解你的意思。很高兴你解决了!
df = pd.DataFrame({
    'zipcode_str': [90210, 90211] ,
    'zipcode_string': [90210, 90211],
})

df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')

df.info()

# you can see that the first column has dtype object
# while the second column has the new dtype string
 #   Column          Non-Null Count  Dtype 
---  ------          --------------  ----- 
 0   zipcode_str     2 non-null      object
 1   zipcode_string  2 non-null      string
dtypes: object(1), string(1)