python - 将 pandas 数据框中的列从 int 转换为 string

标签 python string pandas dataframe int

我在 pandas 中有一个混合了 int 和 str 数据列的数据框。我想首先连接数据框中的列。为此,我必须将 int 列转换为 str。 我尝试过如下操作:

mtrx['X.3'] = mtrx.to_string(columns = ['X.3'])

mtrx['X.3'] = mtrx['X.3'].astype(str)

但在这两种情况下它都不起作用,我收到一条错误消息,提示“无法连接 'str' 和 'int' 对象”。连接两个 str 列效果很好。

最佳答案

In [16]: df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB'))

In [17]: df
Out[17]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [18]: df.dtypes
Out[18]: 
A    int64
B    int64
dtype: object

转换一个系列

In [19]: df['A'].apply(str)
Out[19]: 
0    0
1    2
2    4
3    6
4    8
Name: A, dtype: object

In [20]: df['A'].apply(str)[0]
Out[20]: '0'

别忘了把结果赋值回去:

df['A'] = df['A'].apply(str)

转换整个帧

In [21]: df.applymap(str)
Out[21]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [22]: df.applymap(str).iloc[0,0]
Out[22]: '0'

df = df.applymap(str)

关于python - 将 pandas 数据框中的列从 int 转换为 string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17950374/

相关文章:

python:如何从一天内的时间步中获取最大聚合值?

python - LinkedIn JS API token 交换为 REST token

python - python 中的正则表达式不起作用 - 在 pythex 中有效,但在 python 3.6 中无效

c - 如何将 "strings"的数组放入 C 中的字符数组中?

C++:加入一个 WCHAR[] 数组?

python - 如何在不复制数据的情况下连接 pandas DataFrames?

python - date_hierarchy 中的 Django Admin NonExistentTimeError

python - 在 Python 中跳过多行

java - lastIndexOf() 查找最后一个字母数字字符

python - 使用新数据将列添加到数据帧?