在pandas数据帧中将多个列转换为字符串

Say*_*ti 5 python python-2.7 pandas

我有一个具有不同数据类型的pandas数据框.我想将数据框中的多个列转换为字符串类型.我已经为每个专栏单独完成了但是想知道是否有一种有效的方法?

所以目前我正在做这样的事情:

repair['SCENARIO']=repair['SCENARIO'].astype(str)

repair['SERVICE_TYPE']= repair['SERVICE_TYPE'].astype(str)
Run Code Online (Sandbox Code Playgroud)

我想要一个可以帮助我传递多个列并将它们转换为字符串的函数.

小智 22

我知道这是一个老问题,但我一直在寻找一种方法将所有具有对象数据类型的列转换为字符串,作为我在 rpy2 中发现的错误的解决方法。我正在处理大型数据框,因此不想明确列出每一列。这似乎对我很有效,所以我想我会分享,以防它对其他人有帮助。

stringcols = df.select_dtypes(include='object').columns
df[stringcols] = df[stringcols].fillna('').astype(str)
Run Code Online (Sandbox Code Playgroud)

“fillna('')”通过替换为空字符串来防止 NaN 条目转换为字符串“nan”。


sud*_*nym 14

要将多个列转换为字符串,请在上述命令中包含列的列表:

df[['one', 'two', 'three']] = df[['one', 'two', 'three']].astype(str)
# add as many column names as you like.
Run Code Online (Sandbox Code Playgroud)

这意味着转换所有列的一种方法是构造列的列表,如下所示:

all_columns = list(df) # Creates list of all column headers
df[all_columns] = df[all_columns].astype(str)
Run Code Online (Sandbox Code Playgroud)

请注意,后者也可以直接完成(参见注释).

  • 对于所有列,df = df.astype(str)怎么样? (4认同)