我有一个不同数据类型的pandas数据框。我要将数据帧中的多个列转换为字符串类型。我已经为每个专栏单独做了,但想知道是否有一个有效的方法?
所以目前我正在做这样的事情:
repair['SCENARIO']=repair['SCENARIO'].astype(str)
repair['SERVICE_TYPE']= repair['SERVICE_TYPE'].astype(str)
我需要一个函数来帮助我传递多个列并将它们转换为字符串。
最佳答案
要将multiple列转换为字符串,请将列列表包含到上述命令中:
df[['one', 'two', 'three']] = df[['one', 'two', 'three']].astype(str)
# add as many column names as you like.
这意味着转换all列的一种方法是构造这样的列列表:
all_columns = list(df) # Creates list of all column headers
df[all_columns] = df[all_columns].astype(str)
注意,后者也可以直接完成(见注释)。
关于python - 在pandas数据框中将多列转换为字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50847374/