简体   繁体   English

如何导入多个 csv 文件,根据 Python 中的 csv 文件仅选择我想要的列

[英]How to import multiple csv files selecting only the columns I want depending on the csv files in Python

How to import multiple csv files choosing only the first column in the first csv file and choosing only the second columns for the remaining csv files?如何导入多个 csv 文件,仅选择第一个 csv 文件中的第一列,而仅选择其余 csv 文件的第二列?

Here is what I've done so far:这是我到目前为止所做的:
After I import multiple csv files using glob :在我使用glob导入多个 csv 文件后:

all_files = glob.glob('*.csv')

I used the below code to extract only the second columns from all the imported csv files:我使用以下代码仅从所有导入的 csv 文件中提取第二列:

def read_1st(col):
    return pd.read_csv(col, usecols=[1])

However, how do I selectively import only the first column in the first csv file and only import the second column for the remaining csv files?但是,如何有选择地仅导入第一个 csv 文件中的第一列,而仅导入其余 csv 文件的第二列?

Just load the first .csv seperatly from other .csv`s and then define a function to return only the first row as you did:只需从其他 .csv 文件中单独加载第一个 .csv 文件,然后像您一样定义一个仅返回第一行的函数:

def read_csv(col):
   return pd.read_csv('col',usecols[0])

def read_csv_second(col):
   return pd.read_csv('col',usecols[1])

df1=read_csv(col)
df2=read_csv_second(col)

After that you can concat them together to get the result:之后,您可以将它们连接在一起以获得结果:

df=pd.concat([df1,df2])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM