【问题标题】:Delete the first column from a csv file in Python [duplicate]从Python中的csv文件中删除第一列[重复]
【发布时间】:2019-07-02 22:41:32
【问题描述】:

我在 Python 中有以下代码从 in_folder 文件夹中的 csv 文件中删除第一行,然后将它们保存在文件夹 out_folder 中。现在我需要删除 csv 文件的第一列。有谁知道怎么做?

import csv
import glob
import os
import shutil

path = 'in_folder/*.csv'
files=glob.glob(path)

#Read every file in the directory

x = 0 #counter

for filename in files:

    with open(filename, 'r') as fin:
        data = fin.read().splitlines(True)

        with open(filename, 'w') as fout:
            fout.writelines(data[1:])
            x+=1
            print(x)

dir_src = "in_folder"
dir_dst = "out_folder"


for file in os.listdir(dir_src):
    if x>0:
        src_file = os.path.join(dir_src, file)
        dst_file = os.path.join(dir_dst, file)
        shutil.move(src_file, dst_file)

【问题讨论】:

  • 有很多方法可以做到这一点。你导入csv 却不使用?
  • 是的,现在我注意到我不使用它了。

标签: python file csv


【解决方案1】:

您可以做的是使用Pandas,因为它可以实现DataFrame 操作。

文件.csv

1,2,3,4,5
1,2,3,4,5
1,2,3,4,5

你的代码应该是这样的

import pandas as pd
df = pd.read_csv('file.csv')
# If you know the name of the column skip this
first_column = df.columns[0]
# Delete first
df = df.drop([first_column], axis=1)
df.to_csv('file.csv', index=False)

文件.csv

2,3,4,5
2,3,4,5
2,3,4,5

【讨论】:

  • 我试过了,它保存了一个新文件,但第一列没有被删除。
  • index=False 添加到to_csv 函数中,并确保将删除的数据框分配给变量。
  • 现在可以了,谢谢!
  • pd.read_csv 不是read_csv
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-30
  • 1970-01-01
  • 2020-09-17
  • 2012-07-19
  • 2020-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多