pandas Python - 如何从 excel 列创建列表

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

Python - How to create a list from an excel column

pandas

提问by Pie Junkie

I have a list of names in one column of a csv file. I'm trying to make this into a list in python that looks like

我在 csv 文件的一列中有一个名称列表。我试图把它变成一个 python 中的列表,看起来像

list = ['name1', 'name2', 'name3']

and so on.

等等。

I have the following

我有以下

import pandas as pd
export = pd.read_csv('Top100.csv', header=None)

but I can't figure out how to pull out the information and put it into a list format.

但我不知道如何提取信息并将其放入列表格式。

采纳答案by Greg Jennings

The below is applicable if your data is in a vertical column

如果您的数据在垂直列中,则以下适用

export = pd.read_csv('Top100.csv', header=None)
export.values.T[0].tolist()

The .Tin this transposes the values, as normally pandas is row oriented. Then you take the [0] index because Pandas reads excel or csv sheets in as a matrix, even if there's only a single column. Call the tolist()method on it and you're done.

.T在此调换的值,因为通常是大Pandas行定向。然后你采用 [0] 索引,因为 Pandas 将 excel 或 csv 表作为矩阵读取,即使只有一列。调用tolist()它的方法就完成了。

回答by Adam Hughes

Read csv will return a pandas dataframe so your columns can be accessed through the dataframe. Say your file has columns "A", "B", "C"

Read csv 将返回一个 Pandas 数据框,以便您可以通过数据框访问您的列。假设您的文件包含“A”、“B”、“C”列

import pandas as pd
data = pd.read_csv('Top100.csv', header=None)
print data["a"]

Or as a list

或者作为列表

print list(data["a"])