在 Pandas 数据框中将多列转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50847374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:41:47  来源:igfitidea点击:

Convert multiple columns to string in pandas dataframe

pythonpython-2.7pandas

提问by Sayonti

I have a pandas data frame with different data types. I want to convert more than one column in the data frame to string type. I have individually done for each column but want to know if there is an efficient way?

我有一个具有不同数据类型的Pandas数据框。我想将数据框中的一列以上转换为字符串类型。我已经为每一列单独做了,但想知道是否有一种有效的方法?

So at present I am doing something like this:

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

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

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

I want a function that would help me pass multiple columns and convert them to strings.

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

回答by sudonym

To convert multiplecolumns to string, include a listof columns to your above-mentioned command:

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

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

That means that oneway to convert allcolumns is to construct the list of columns like this:

这意味着转换所有列的一种方法是构造这样的列列表:

all_columns = list(df) # Creates list of all column headers
df[all_columns] = df[all_columns].astype(str)

Note that the latter can also be done directly (see comments).

请注意,后者也可以直接完成(见评论)。

回答by Amir F

You can also use list comprehension:

您还可以使用列表理解:

[df[col_name].astype(str) for col_namein df.columns]

You can also insert a condition to test if the columns should be converted - for example:

您还可以插入一个条件来测试是否应转换列 - 例如:

[df[col_name].astype(str) for col_namein df.columns if 'to_str' in col_name]