python-2.7 - 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")
解决方案
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")
看看这是否适合你。
如果您不知道如何查找具有特定扩展名的所有文件,请查看此处。
推荐阅读
- python - Pandas Multiindex 在级别上重新索引
- ng-dropdown-multiselect - 如何从我的服务中填写我的下拉列表?
- networking - 从同一网络中的另一台计算机复制文件夹而无需密码
- angular - 使用 Bazel 构建 Angular7 项目
- random-forest - 在嵌套重采样中,分类精度结果变化很大
- yajra-datatable - 使用 php artisan serve 运行运行 yajra 数据表时出现内部服务器错误
- c++ - 受保护的成员访问检查可以使用 static_cast 来破坏吗?
- python - 如何使用 %s 在 python 中为 Selenium 构造一个带有变量的 xpath 表达式
- python - ValueError:预期的二维数组,而不是一维数组。训练模型
- django - 为单个 Django 查询关闭 Postgres 并行查询