如何使用pandas清理多个数据

2024-09-28 17:15:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据文件夹,包含“admin,admin1…admin500”,我想删除标题并向数据中添加列名

df = pd.read_csv('admin.tsv', comment='#', header=None, sep='\t',names=['index','count','text','tag'])

如何使用for循环执行该文件夹中的每个文件,并将它们保存为与以前相同的名称


Tags: csv数据文件夹none标题dfreadadmin
2条回答

尝试使用os

import os

path = "C:/Users/username"
files = [file for file in os.listdir(path) if file.endswith(".tsv")]

for file in files:
    df = pd.read_csv(os.path.join(path, file), 
                     comment='#', 
                     header=None, 
                     sep='\t',
                     names=['index','count','text','tag'])
    df.to_csv(os.path.join(path, file))

注意:如您问题中所述,这将用修改的df覆盖现有文件

import glob
for file in glob.glob('foldername/*'):
    df = pd.read_csv(file, comment='#', header=None, sep='\t',names=['index','count','text','tag'])
    df.to_csv(f'./tmp/{file}')

我假设代码将在相同的数据文件夹中执行,请注意,您可以将.glob.glob('.')中的数据文件夹关联起来

结果将保存在tmp文件夹中

相关问题 更多 >