pandas Python:将数据帧转换为列表中包含字符串项的列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41768196/
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 02:49:52  来源:igfitidea点击:

Python: Convert dataframe into a list with string items inside list

pythonpandasdataframe

提问by PineNuts0

I currently have code that reads in an Excel table (image below):

我目前有读取 Excel 表格的代码(下图):

# Read in zipcode input file

us_zips = pd.read_excel("Zipcode.xls")
us_zips

enter image description here

在此处输入图片说明

I use the following code to convert the dataframe zip codes into a list:

我使用以下代码将数据框邮政编码转换为列表:

us_zips = list(us_zips.values.flatten())

When I print us_zips it looks like this:

当我打印 us_zips 时,它看起来像这样:

[10601, 60047, 50301, 10606]

[10601、60047、50301、10606]

...but I want it to look like this ["10601", "60047", "50301", "10606"]

...但我希望它看起来像这样 ["10601", "60047", "50301", "10606"]

How can I do that? *Any help is greatly appreciated

我怎样才能做到这一点?*任何帮助是极大的赞赏

采纳答案by EdChum

You can just cast the column dtype using astype(str)and then convert to list using .values.tolist(), this returns a numpy array using .valueswhich has a member function to convert this to a list:

您可以只使用 dtypeastype(str)转换列,然后使用转换为列表.values.tolist(),这将返回一个 numpy 数组 using .values,它具有将其转换为列表的成员函数:

In [321]:
us_zips['zipcode'].astype(str).values.tolist()

Out[321]:
['10601', '60047', '50301', '10606']

回答by Tom Hale

It worked for me without .values():

它对我有用,没有.values()

list = df[col_name].astype(str).tolist()