2024-04-25 23:24:44 发布
网友
我在pandas中有一个混合了int和str数据列的dataframe。我想先连接数据帧中的列。为此,我必须将int列转换为str。 我试着做以下事情:
int
str
mtrx['X.3'] = mtrx.to_string(columns = ['X.3'])
或者
mtrx['X.3'] = mtrx['X.3'].astype(str)
但在这两种情况下都不起作用,我得到一个错误,说“不能连接'str'和'int'对象”。连接两个str列工作得非常好。
更改数据帧列的数据类型:
内景:
df.column_name = df.column_name.astype(np.int64)
发送到str:
df.column_name = df.column_name.astype(str)
警告:给出的两个解决方案均不保留nan或None形式的空值。
import pandas as pd import numpy as np df = pd.DataFrame([None,'string',np.nan,42], index=[0,1,2,3], columns=['A']) df1 = df['A'].astype(str) df2 = df['A'].apply(str) print df.isnull() print df1.isnull() print df2.isnull()
我相信这是通过实现to_string()来解决的
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)
更改数据帧列的数据类型:
内景:
df.column_name = df.column_name.astype(np.int64)
发送到str:
df.column_name = df.column_name.astype(str)
警告:给出的两个解决方案均不保留nan或None形式的空值。
我相信这是通过实现to_string()来解决的
转换序列
不要忘记将结果分配回:
转换整个帧
相关问题 更多 >
编程相关推荐