简体   繁体   English

Pandas:将列名添加到多个 csv 文件的第三列

[英]Pandas: Add column name to third column for multiple csv files

I have multiple csv files in same directory.我在同一目录中有多个 csv 文件。 Each csv file contains 3 columns but in 3rd column, column name is missing.每个 csv 文件包含 3 列,但在第 3 列中,缺少列名。 To read all csv files I had to use error_bad_lines=False .要读取所有 csv 个文件,我必须使用error_bad_lines=False Now, I want to add column name c3 to third column for multiple csv files.现在,我想将列名c3添加到多个 csv 文件的第三列。

Sample df:样本 df:

v     info  
12    days    6
53    x       a
42    y       b 

Expected output:预计 output:

    v    info   c3
0  12    days    6
1  53    x       a
2  42    y       b 

First, convert index "v" into column首先,将索引“v”转换为列

df = df.reset_index()

Then, you can change the columns simply.然后,您可以简单地更改列。

df.columns = ["v", "info", "c3"]

Finally,最后,

import pandas as pd
for file in os.listdir(directory):
    if file.endswith(".csv"):
        df = pd.read_csv(file)
        df = df.reset_index() # this is option line
        df.columns = ["v", "info", "c3"]
        df.to_csv(file)


        

Not sure how your csv looks like, so I assumed that your csv would be:不确定你的 csv 长什么样,所以我假设你的 csv 是:

v,info,
12,days,6
53,x,a
42,y,b

Whatever, you can load all the csv file in a directory and change column names as follows:不管怎样,您可以将所有 csv 文件加载到一个目录中并更改列名,如下所示:

import pandas as pd
import glob

for f in glob.glob("C:\*.csv"):
    print(f)  # f is a file name
    df = pd.read_csv(f)
    df.reset_index() # add index column, 0, 1, 2, ...
    df.columns = ['v', 'info', 'c3'] # change column names
    df.to_csv(f)  # save it (overwriting)

You can see how to use glob to load files in a directory in detail here: https://www.geeksforgeeks.org/how-to-use-glob-function-to-find-files-recursively-in-python/您可以在此处详细了解如何使用glob加载目录中的文件: https://www.geeksforgeeks.org/how-to-use-glob-function-to-find-files-recursively-in-python/

Use:利用:

a = pd.DataFrame({'v': [12,53,42], 'info':['days','x','y'], '':[6,'a','b']})
cols = list(a.columns)[:2]
cols.append('col3')
a.columns = cols
a

output: output:

在此处输入图像描述

or, simply:或者,简单地说:

a.rename(columns={'':'new'})

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

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