【问题标题】:Concatenate multiple unequal dataframes on condition根据条件连接多个不相等的数据帧
【发布时间】:2019-05-24 11:08:14
【问题描述】:

我有 7 个数据帧(df_1、df_2、df_3、...、df_7),它们都具有相同的列,但长度不同,但有时具有相同的值

我想在 条件 下连接所有 7 个数据帧:

if df_n.iloc[row_i] != df_n+1.iloc[row_i] and df_n.iloc[row_i][0] < df_n+1.iloc[row_i][0]:

      pd.concat([df_n.iloc[row_i], df_n+1.iloc[row_i], df_n+2.iloc[row_i],
      ...., df_n+6.iloc[row_i]])

df_n.iloc[row_i] 是第 n 个数据帧的第 i 行,df_n.iloc[row_i][0] 是第 i 行的第一列。

例如,如果我们只有 2 个数据帧并且 len(df_1) len(df_2) 并且如果我们使用 上述条件,则 输入 将是:

df_1                                    df_2

index    0      1       2               index    0        1       2
0        12.12  11.0    31              0        12.2     12.6    30
1        12.3   12.1    33              1        12.3     12.1    33
2        10     9.1     33              2        13       12.1    23
3        16     12.1    33              3        13.1     12.1    27
                                        4        14.4     13.1    27
                                        5        15.2     13.2    28

输出将是:

conditions -> pd.concat([df_1, df_2]):

index    0      1       2      3      4      5     
0        12.12  11.0    31     12.2   12.6   30
2        10     9.1     33     13     12.1   23
4        nan                   14.4   13.1   27
5        nan                   15.2   13.2   28

有没有简单的方法可以做到这一点?

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    IIUC concat 首先,groupby by 列得到不同,我们只是实现你的条件

    s=pd.concat([df1,df2],1)
    s1=s.groupby(level=0,axis=1).apply(lambda x : x.iloc[:,0]-x.iloc[:,1])
    yourdf=s[s1.ne(0).any(1)&s1.iloc[:,0].lt(0)|s1.iloc[:,0].isnull()]
    Out[487]: 
               0     1     2     0     1   2
    index                                   
    0      12.12  11.0  31.0  12.2  12.6  30
    2      10.00   9.1  33.0  13.0  12.1  23
    4        NaN   NaN   NaN  14.4  13.1  27
    5        NaN   NaN   NaN  15.2  13.2  28
    

    【讨论】:

      猜你喜欢
      • 2015-12-29
      • 2018-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      • 2021-04-18
      • 2020-05-23
      • 1970-01-01
      相关资源
      最近更新 更多