简体   繁体   English

如何使用 python 遍历目录并从所有 csvs 中删除特定列?

[英]How do use python to iterate through a directory and delete specific columns from all csvs?

I have a directory with several csvs.我有一个包含多个 csv 的目录。

files = glob('C:/Users/jj/Desktop/Bulk_Wav/*.csv')

Each csv has the same below columns.每个 csv 都有相同的下面的列。 Reprex below-下面的reprex-

yes no maybe ofcourse
1   2  3     4

I want my script to iterate through all csvs in the folder and delete the columns maybe and ofcourse.我希望我的脚本遍历文件夹中的所有 csvs 并删除列。

Do you mean by:你的意思是:

files = glob('C:/Users/jj/Desktop/Bulk_Wav/*.csv')
for filename in files:
    df = pd.read_csv(filename)
    df = df.drop(['maybe ', 'ofcourse'], axis=1)
    df.to_csv(filename)

This code will remove the maybe and ofcourse columns and save it back to the csv.此代码将删除maybeofcourse列并将其保存回csv。

If glob provides you with file paths, you can do the following with pandas :如果glob为您提供了文件路径,您可以使用pandas执行以下操作:

import pandas as pd

files = glob('C:/Users/jj/Desktop/Bulk_Wav/*.csv')
drop = ['maybe ', 'ofcourse']

for file in files:
    df = pd.read_csv(file)
    for col in drop:
        if col in df:
            df = df.drop(col, axis=1)
    df.to_csv(file)

Alternatively if you want a cleaner way to not get KeyError s from drop you can do this:或者,如果您想要一种更KeyError的方式来避免从 drop 中获取KeyError s,您可以这样做:

import pandas as pd

files = glob('C:/Users/jj/Desktop/Bulk_Wav/*.csv')
drop = ['maybe ', 'ofcourse']

for file in files:
    df = pd.read_csv(file)
    df = df.drop([c for c in drop if c in df], axis=1)
    df.to_csv(file)

You can use panda to read csv file to a dataframe then use drop() to drop specific columns.您可以使用 panda 将 csv 文件读取到数据帧,然后使用 drop() 删除特定列。 something like below:像下面这样:

df = pd.read_csv(csv_filename)
df.drop(['maybe', 'ofcourse'], axis=1)
import pandas as pd
from glob import glob

files = glob(r'C:/Users/jj/Desktop/Bulk_Wav/*.csv')
for filename in files:
    df = pd.read_csv(filename, sep='\t')
    df.drop(['maybe', 'ofcourse'], axis=1, inplace=True)
    df.to_csv(filename, sep='\t', index=False)

If the files look exactly like what you have there, then maybe something like this如果文件看起来和你在那里的完全一样,那么可能是这样的

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

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