繁体   English   中英

将仅一个值(例如:实验条件名称)的单列添加到单个文件夹中的多个csv文件

[英]Adding a single column of only one value( eg: Experiment condition name) to multiple csv files in a single folder

我有一个包含多个csv文件的文件夹,我想向该文件夹中的所有csv文件中添加一列具有实验条件名称的列。

import os, pandas as pd
import csv
file_list = list()
os.chdir('.....name.../')
g=[]
for file in os.listdir():
    if file.endswith('.csv'):
        df = pd.read_csv(file)
        df['Condition'] = "After food"
        file_list.append(df)
        g.append(file_list)

如果我对您的理解正确,则您的问题是保存回csv文件。 如果要这样做,可以在循环函数中使用函数to_csv:

df.to_csv(file)

告诉我这是否不是您的意思,我会尽力帮助您。

假设您已经在正确的目录中,我们可以尝试这样的操作:

首先,我们将所有csv文件传递到列表中

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

然后,我们可以通过方便的tryexcept语句遍历此列表以查找您的列。

for file in files:
    df = pd.read_csv(file)
    try:
        df['Condition'] == "After food"
        # do something.
        df.to_csv(f'{file}.csv',index=False)
        print(f'{file} has been altered')
    except KeyError:
        print(f'{file} has not met the condition, therefore has not been changed.')
    except EmptyDataError:
        print(f"this {file} has no data to parse")

输出将是这样的:

PayCodes.csv has been altered
birmingham.csv has not met the condition
CF44.csv has not met the condition
DE11.csv has not met the condition
Dublin.csv has not met the condition
DY8.csv has not met the condition

暂无
暂无

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

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