Python:将数据框转换为列表,列表中包含字符串项 [英] Python: Convert dataframe into a list with string items inside list
问题描述
我目前有读取Excel表中的代码(下图):
I currently have code that reads in an Excel table (image below):
# Read in zipcode input file
us_zips = pd.read_excel("Zipcode.xls")
us_zips
我使用以下代码将数据框的邮政编码转换为列表:
I use the following code to convert the dataframe zip codes into a list:
us_zips = list(us_zips.values.flatten())
当我打印us_zips时,它看起来像这样:
When I print us_zips it looks like this:
[10601、60047、50301、10606]
[10601, 60047, 50301, 10606]
...但是我希望它看起来像这样["10601","60047","50301","10606"]
...but I want it to look like this ["10601", "60047", "50301", "10606"]
我该怎么做? *非常感谢您的帮助
How can I do that? *Any help is greatly appreciated
推荐答案
您可以使用 .values
具有成员函数,可将其转换为列表:
You can just cast the column dtype using astype(str)
and then convert to list using .values.tolist()
, this returns a numpy array using .values
which has a member function to convert this to a list:
In [321]:
us_zips['zipcode'].astype(str).values.tolist()
Out[321]:
['10601', '60047', '50301', '10606']
这篇关于Python:将数据框转换为列表,列表中包含字符串项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!