按条件连接多个不相等的数据帧

2024-10-03 15:30:05 发布

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

我有7个数据帧(dfu 1,df u 2,df u 3,…,df u 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

有什么简单的方法吗


Tags: and数据dfindexlenifnan条件
1条回答
网友
1楼 · 发布于 2024-10-03 15:30:05

IIUCconcat首先,groupbyby列得到不同的结果,我们只实现您的条件

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

相关问题 更多 >