使用 pandas 从导入的 CSV 文件创建列表

Creating list from imported CSV file with pandas

我正在尝试从 CSV 创建列表。此 CSV 包含二维 table [540 行和 8 列],我想创建一个列表,其中包含特定列的值,具体来说是第 4 列。

我试过:list(df.columns.values)[4],它确实提到了列的名称,但我试图从第 4 列的行中获取值并将它们制成列表。

import pandas as pd
import urllib
#This is the empty list
company_name = [] 

#Uploading CSV file 
df = pd.read_csv('Downloads\Dropped_Companies.csv')

#Extracting list of all companies name from column "Name of Stock"
companies_column=list(df.columns.values)[4] #This returns the name of the column. 
companies_column = list(df.iloc[:,4].values)

我认为您可以试试这个来获取特定列的所有值:

companies_column = df[{column name}]

将“{column name}”替换为您要访问其值的列。

  1. 为此,您只需在发布的代码后添加以下行:

    company_name = df[companies_column].tolist()
    

    这将 get the column data in the companies column as pandas Series (essentially a Series is just a fancy list) and then convert it to a regular python list

  2. 或者,如果你是从头开始,你也可以只使用这两行

    import pandas as pd
    
    df = pd.read_csv('Downloads\Dropped_Companies.csv')
    company_name = df[df.columns[4]].tolist()
    
  3. 另一种选择:如果这是您需要对 csv 文件做的唯一事情,您也可以使用 python 附带的 csv 库而不是安装 pandas, 使用 .

如果您想详细了解如何从 pandas DataFrame(代码中的 df 变量)中获取数据,您可能会发现 this blog post 很有帮助。