使用 pandas 通过将两列合并为一列来重建数据框

To rebuild a dataframe by combining two columns into one column by using pandas

我想通过将两列合并为一列来重建我的数据框,例如,

>>>df.set_index('df1')  
        0 1 2 3 4 5
df1
GroupA  A D G J M P
GroupB  B E H K N Q
GroupC  C F I L O R   #It is my dataframe.

然后我想看看我的结果如下。

 >>>print result
    df1     0  1  2
    GroupA  AD GJ MP  
    GroupB  BE HK NQ
    GroupC  CF IL OR  

#which means column0 is combined with column1, and 2+3, and 4+5......etc

我只知道可以用concat()合并列,用apply(lambda xxx...)设置合适的函数。

有没有人可以给我提示或知道如何通过在 python 中使用 pandas 来获取它?谢谢,

有点奇怪你要求做什么,但基本上我们可以在步骤 2 中迭代列,然后在 df 的一个小节上调用 sum 并传递 axis=1,这将连接 str 值。一个棘手的问题是您的列是数字,当以这种方式使用方括号时,它会尝试将列名称解析为 str,这意味着 col+1 将不起作用,这就是我将其转换为 [= 的原因15=]:

In [32]:

dfnew = pd.DataFrame()
for col in df.columns[::2]:
    c = int(col)
    dfnew[col] = df[[c,c+1]].sum(axis=1)
dfnew
Out[32]:
         0   2   4
df1               
GroupA  AD  GJ  MP
GroupB  BE  HK  NQ
GroupC  CF  IL  OR

编辑

一种通用方法使用列数的长度来生成整数索引以索引到列数组中并从中提取列名以执行选择,这将适用于您的 df 以及 df 具有的位置海峡名称:

In [26]:

dfnew = pd.DataFrame()
for i in range(len(df.columns))[::2]:
    col_1 = df.columns[i]
    col_2 = df.columns[i+1]
    dfnew[col_1] = df[[col_1,col_2]].sum(axis=1)
dfnew
Out[26]:
         0   2   4
df1               
GroupA  AD  GJ  MP
GroupB  BE  HK  NQ
GroupC  CF  IL  OR