我有几个csv文件,我试图使用pandas加载连接。已经有类似的问题,但答案似乎并没有对我有用。基本上,代码正在加载csv文件并连接,但DF的结构很奇怪(列数意外增长)。一点背景:我是Matlab的新转换器,我实际上已经在Matlab中使用了这段代码,我只想让它在Python中运行。这是代码:
import pandas as pd
import glob
filelist = glob.glob('/.../*.csv')
DF = pd.DataFrame()
list_ = []
for i in filelist:
tmp = pd.read_csv(i, header=1, skiprows=0, index_col=None)
list_.append(tmp)
DF = pd.concat(list_)
DF.to_csv('/.../All.csv')
csv文件的结构如下:
TestDate,City,State,ZipCode,County,Num,A,B,C
9/1/16,X,AL,X,X,29,negative,positive,positive
9/1/16,X,AL,X,X,1,negative,negative,negative
9/1/16,X,AL,X,X,10,negative,negative,negative
输出如下:
,11/14/16,11/7/16,17,29,32,X,71901,9/1/16,99771,AK,AL,AR,X,X,X,X,Nome Census Area,X,negative,negative.1,negative.2,positive,positive.1
0,,,,1.0,,X,,9/1/16,,,AL,,X,X,,,,,negative,,,negative,negative
1,,,,10.0,,X,,9/1/16,,,AL,,X,X,,,,,negative,,,negative,negative
2,,,,11.0,,X,,9/1/16,,,AL,,X,X,,,,,negative,,,negative,negative
答案 0 :(得分:1)
问题是header=1
告诉大熊猫第二行应该被视为标题而不是第一行。
from io import StringIO
import pandas as pd
data="""TestDate,City,State,ZipCode,County,Num,A,B,C
9/1/16,X,AL,X,X,29,negative,positive,positive
9/1/16,X,AL,X,X,1,negative,negative,negative
9/1/16,X,AL,X,X,10,negative,negative,negative"""
df=pd.read_csv(StringIO(data))
print(df)
TestDate City State ZipCode County Num A B C
0 9/1/16 X AL X X 29 negative positive positive
1 9/1/16 X AL X X 1 negative negative negative
2 9/1/16 X AL X X 10 negative negative negative
df=pd.read_csv(StringIO(data),header=1,skiprows=0)
print(df)
9/1/16 X AL X.1 X.2 29 negative positive positive.1
0 9/1/16 X AL X X 1 negative negative negative
1 9/1/16 X AL X X 10 negative negative negative
问题在于,各个数据框的第一行中有许多不同的城市,因此会在DataFrame中插入越来越多的列,这意味着每个相应文件的数据列太少,一切都变得超级凌乱。