我有几个csv格式的文件,例如100-age.csv 100-rel.csv 100-gender.csv 101-age.csv ... 101-gender.csv ... 482-rel.csv 482-gender.csv
等。我必须为每个索引创建新文件,即100-combo.csv
,它将合并100-age.csv 100-rel.csv
和100-gender.csv
水平。我可以使用熊猫对一个文件执行此操作
import pandas as pd
age = pd.read_csv('100-age.csv', header=None)
gender = pd.read_csv('100-gender.csv', header=None)
rel = pd.read_csv('100-rel.csv', header=None)
combined = pd.concat([age, gender, rel], axis=1)
combined.to_csv('100-combo.csv', header=None, index=None)
使用Linux,有cat
之类的方法只能垂直添加,即彼此堆叠,而paste
的命令会干扰我在这些文件中的格式。
def merged_data(i):
age = pd.read_csv(path+str(i)+'.pdf-age.csv', header=None, error_bad_lines=False)
gender = pd.read_csv(path+str(i)+'.pdf-gender.csv', header=None, error_bad_lines=False)
rel = pd.read_csv(path+str(i)+'.pdf-rel.csv', header=None, error_bad_lines=False)
combined = pd.concat([age, gender, rel], axis=1)
combined['block'] = str(i)
combined.to_csv(path+str(i)+'-combo.csv', header=None, index=None)
for num in range(1,483):
merged_data(num)
我收到此错误
EmptyDataError: No columns to parse from file
但是,我知道我所有的数据文件都有一些或其他值
答案 0 :(得分:1)
我做到了,得到了我想要的。我用
import pandas as pd
import numpy as np
from pandas.io.common import EmptyDataError
def merged_data(i):
try:
age = pd.read_csv(path+str(i)+'.pdf-age.csv', header=None, error_bad_lines=False, delim_whitespace=True)
except EmptyDataError:
age = pd.DataFrame()
try:
gender = pd.read_csv(path+str(i)+'.pdf-gender.csv', header=None, error_bad_lines=False, delim_whitespace=True)
except EmptyDataError:
gender = pd.DataFrame()
try:
rel = pd.read_csv(path+str(i)+'.pdf-rel.csv', header=None, error_bad_lines=False, delim_whitespace=True)
except EmptyDataError:
rel = pd.DataFrame()
combined = pd.concat([age, gender, rel], axis=1)
combined['block'] = str(i)
combined.to_csv(path+str(i)+'-combo.csv', header=None, index=None)
for num in range(1,483):
merged_data(num)