合并3个或更多数据框

时间:2020-05-05 05:51:23

标签: python pandas

我正在尝试按索引合并3个数据帧,但到目前为止没有成功。

代码如下:

Private Sub IMRecomExIns_Click()
    Dim db As DAO.Database
    Dim rsData As DAO.Recordset
    Dim strSQL As String
    Set db = DBEngine(0)(0)
    strSQL = "SELECT Recommendation, AmendReason FROM Table2 WHERE CoverType LIKE '*" & Me!cboCover & "*';"
    Set rsData = db.OpenRecordset(strSQL)
    If Not (rsData.BOF And rsData.EOF) Then
        Me!IMRecomExIns.RowSource = rsData!Recommendation
        Me!AmendReasonExIns.RowSource = rsData!AmendReason
    End If
    rsData.Close
    Set rsData = Nothing
    Set db = Nothing
End Sub

如果我尝试将其导出为csv,则会收到如下错误(当我尝试打印dfx.columns时出现类似错误): 'tuple'对象没有属性'to_csv'

我想要的输出是以下三个数据框的合并(带有各自的后缀),请提供帮助。

[注:下面的表非常简化,原始表由数十列和数千行组成,因此需要实用的合并方法]

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试:

for s,el in zip(suffixes, dfs):
    el.columns=[str(col)+s for col in el.columns]

dfx=pd.concat(dfs, ignore_index=True, sort=False, axis=1)

对于我使用的测试用例:

import pandas as pd

dfs=[pd.DataFrame({"x": [1,2,7], "y": list("ghi")}), pd.DataFrame({"x": [5,6], "z": [4,4]}), pd.DataFrame({"x": list("acgjksd")})]

suffixes=["_1", "_2", "_3"]

for s,el in zip(suffixes, dfs):
    el.columns=[str(col)+s for col in el.columns]

>>> pd.concat(dfs, ignore_index=True, sort=False, axis=1)

   x_1  y_1  x_2  z_2 x_3
0  1.0    g  5.0  4.0   a
1  2.0    h  6.0  4.0   c
2  7.0    i  NaN  NaN   g
3  NaN  NaN  NaN  NaN   j
4  NaN  NaN  NaN  NaN   k
5  NaN  NaN  NaN  NaN   s
6  NaN  NaN  NaN  NaN   d


修改

for s,el in zip(suffixes, dfs):
    el.columns=[str(col)+s for col in el.columns]
    el.set_index('ID', inplace=True)

dfx=pd.concat(dfs, ignore_index=False, sort=False, axis=1).reset_index()