我有几十个csv文件头相似(但并不总是完全相同)。例如,有:
Year Month Day Hour Minute Direct Diffuse D_Global D_IR Zenith Test_Site
其中之一是:
^{pr2}$(请注意,一个缺少“UüGlobal”和“UüIR”,另一个没有“Diffuse2”而不是“Diffuse2”)
我知道如何将多个csv传递到我的脚本中,但是如何让csv的唯一传递值传递给它们当前有值的列?或许可以将“Nan”传递给该行中的所有其他列。在
理想情况下,我会有一些类似的东西:
'Year','Month','Day','Hour','Minute','Direct','Diffuse','Diffuse2','D_Global','D_IR','U_Global','U_IR','Zenith','Test_Site'
1992,1,1,0,3,-999.00,-999.00,"Nan",-999.00,-999.00,"Nan","Nan",122.517,"BER"
2013,5,30,15,55,812.84,270.62,"Nan",1078.06,-999.00,"Nan","Nan",11.542,"BER"
2004,9,1,0,1,1.04,79.40,"Nan",78.67,303.58,61.06,310.95,85.142,"ALT"
2014,12,1,0,1,0.00,0.00,"Nan",-999.00,226.95,0.00,230.16,115.410,"ALT"
另一个警告是,需要附加此数据帧。它需要保留,因为有多个csv文件传入它。我想我可能会在最后把它写成自己的csv(它最终会变成NETCDF4)。在
熊猫不能自动处理吗?在
http://pandas.pydata.org/pandas-docs/stable/merging.html#concatenating-using-append
如果您的索引重叠,请不要忘记添加“ignore_index=True”
假设您有以下CSV文件:
测试1.csv:
测试2.csv:
^{pr2}$测试3.csv:
解决方案:
输出:
更新:通常惯用的
pd.concat(list_of_dfs)
解决方案在这里不起作用,因为它是通过索引连接的:或显式使用
index_col=None
:以下更惯用的解决方案有效,但它改变了列和行/数据的原始顺序:
首先,运行所有文件以定义公共头:
然后将标题行写入输出文件,并再次运行所有文件以填充它。在
您可以使用:
csv.DictReader(open('myfile.csv'))
来简单地将标题与它们指定的列相匹配。在相关问题 更多 >
编程相关推荐