首页 > 解决方案 > Python - 根据文件名将其他excel文件中的特定列复制到新的列

问题描述

我有一个脚本,它生成 CSV 文件并根据时间戳命名它们

-rw-rw-r-- 1 9949 Oct 13 11:57 2018-10-13-11:57:10.796516.csv
-rw-rw-r-- 1 9649 Oct 13 12:58 2018-10-13-12:58:12.907835.csv
-rw-rw-r-- 1 9649 Oct 13 13:58 2018-10-13-13:58:10.502635.csv

我需要从这些工作表中选择 C ​​列并写入一个新的 CSV 文件。但是,新工作表中的列顺序应与现有工作表的名称一致。例如,在 11:57 生成的文件中的 C 列应该在 A 列中,从 B 列的 12:58 和新工作表的 C 列的 13:38 开始。

编辑——基于 Bilal 输入尝试的代码。它确实将 C 列从所有现有工作表移动到新工作表,但顺序不正确。它只是随机选择它们并不断添加新文件的列。

import os
import re
import pandas as pd

newCSV = pd.DataFrame.from_dict({})

# get a list of your csv files and put them files

files = [f for f in os.listdir('.') if os.path.isfile(f)]

results = []
for f in files:
    if re.search('.csv', f):
        results += [f]

for file in results:
    df = pd.read_csv(file,usecols=[2])

    newCSV = pd.concat((newCSV, df), axis=1)

newCSV.to_csv("new.csv")

编辑——最终代码有效,谢谢比拉尔

import os
import re
import pandas as pd



newCSV = pd.DataFrame.from_dict({})

files = [f for f in os.listdir('.') if os.path.isfile(f)]

# get a list of your csv files and put them files
results = []
for f in files:
        if re.search('.csv', f):
                results += [f]
result1=sorted(results)
for file in result1:
    df = pd.read_csv(file,usecols=[2])

    newCSV = pd.concat((newCSV, df), axis=1)

newCSV.to_csv("new.csv") 

标签: python-2.7csv

解决方案


import pandas as pd

newCSV = pd.DataFrame.from_dict({})

# get a list of your csv files and put them files

for f in files:
    df = pd.read_csv(f)

    newCSV = pd.concat((newCSV, df.colum_name), axis=1)

newCSV.to_csv("new.csv") 

看看这是否适合你。

如果您不知道如何查找具有特定扩展名的所有文件,请查看此处


推荐阅读