匹配列并附加到数据帧,Python3.6

2024-09-30 02:18:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有大约50个excel文件,我想导入dataframe并将所有文件合并到单个dataframe中。 但有些文件有3列,有些是4列。每个文件以不同的顺序作为不同的列。在

所有文件的全部不同列:5,即col1、col2、col3、col4、col5

我知道如何导入,但在附加时面临问题。在

脚本:

dfAll = pd.DataFrame(columns=['col1', 'col2', 'col3', 'col4', 'col5')]
df= pd.read_excel('FilePath', sheetname='data1') # contains 3 columns i.e col1, col2, col5
columnsOFdf = df.columns
dfAll[columnsOFdf] = dfAll.append(df)

但它给出的错误是“ValueError:Columns must be same length as key”

我想将df['col1','col2','col5']数据附加到dfAll['col1','col2','col5']

请帮助解决这个问题。在


Tags: columns文件脚本dataframedf顺序excelcol2
3条回答

一种解决方案是将空列添加到从Excel文件加载的数据帧中:

columns = ['col1', 'col2', 'col3', 'col4', 'col5']
dfAll = pd.DataFrame(columns=columns)
df= pd.read_excel('FilePath', sheetname='data1') # contains 3 columns i.e             col1, col2, col5
columnsOFdf = df.columns
for column in columns:
    if column not in columnsOFdf:
        df[column] = [""] * df.shape[0]
dfAll.append(df)

试试这个:

[dfAll.append(i) for i in df]

我希望这对你有帮助。在

连接将匹配您的列

dfs = []
files = [...]
for file_name in files:
    dfs.append(pd.read_excel(file_name, sheetname='data1'))
df = pd.concat(dfs)

df1 = pd.DataFrame(np.random.randn(3, 3), columns=list('ABC'))
df2 = pd.DataFrame(np.random.randn(3, 3), columns=list('BCD'))
>>> pd.concat([df1, df2])
          A         B         C         D
0 -2.329280  0.644155 -0.835137       NaN
1  0.666496 -1.299048  0.111579       NaN
2  1.855494 -0.085850 -0.541890       NaN
0       NaN -1.131514  1.023610 -0.514384
1       NaN  0.670063  1.403143 -0.978611
2       NaN -0.314741 -0.727200 -0.620511

此外,每次将数据帧附加到现有帧后,它都会返回一个copy。这将严重降低性能,称为二次拷贝。最好创建一个包含所有数据帧的列表,然后连接结果。在

相关问题 更多 >

    热门问题