Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中组合多个列_Python_Pandas - Fatal编程技术网

如何在python中组合多个列

如何在python中组合多个列,python,pandas,Python,Pandas,我想在python数据框架中将中的每5列组合在一起,以便组合1-5列,组合6-10列,以此类推 df看起来像 D1-7 D1-8 D1-9 D1-10 D1-11 D2-7 D2-8 D2-9 D2-10 D2-11 1 0 1 1 1 1 1 0 0 1 0 1 1 0 1 1 0 1 1 0 比如,你想要什么 D1-7-11 D2-7-12 10111 11001 0

我想在python数据框架中将中的每5列组合在一起,以便组合1-5列,组合6-10列,以此类推

df看起来像

D1-7 D1-8 D1-9 D1-10 D1-11 D2-7 D2-8 D2-9 D2-10 D2-11
1    0    1    1     1     1    1    0    0     1
0    1    1    0     1     1    0    1    1     0
比如,你想要什么

D1-7-11 D2-7-12
10111   11001
01101   10110
更新:

df = df.astype(str) #Just make sure dtype object in dataframe
df.groupby([i // 5 for i in map(df.columns.get_loc, df.columns)], axis=1)\
  .apply(lambda x: pd.Series([''.join(i) for i in x.values]))
输出:

       0      1
0  10111  11001
1  01101  10110
       0      1
0  10111  11001
1   1101  10110
尝试:

输出:

       0      1
0  10111  11001
1  01101  10110
       0      1
0  10111  11001
1   1101  10110
说明:

使用pd.DataFrame.columns中的get_loc方法获取每个列的索引位置以及映射

然后,使用\\floordiv by 5将列按5分组


使用groupby和参数axis=1,我们可以对每个组中的字符串值求和、连接。然后,将结果强制转换为整数,使用astype去除小数点零。

没有比上面更简洁的了,但是可以尝试以下方法:

for i in enumerate(np.array_split(df.columns.tolist(), np.ceil(len(df.columns)/5))):
        df['combo'+str(i[0])] = df[i[1]].apply(lambda x: ','.join(x.dropna().astype('unicode')), axis=1)

将列拆分为5个块,在列表中循环并使用“,”将它们连接在一起。要执行任务,请按以下步骤进行:

获取列名列表:

cc = df.columns
创建分组映射。目标列将为C0、C1、…:

定义连接函数,将一系列int转换为 一系列str并将其连接:

def myJoin(x):
    return ''.join(x.astype(str).values)
最后,执行您的加入:

df.groupby(grp, axis=1).agg(lambda x: myJoin(x))
出于演示目的,我创建了测试数据帧,如下所示:

   D1-7  D1-8  D1-9  D1-10  D1-11  D2-7  D2-8  D2-9  D2-10  D2-11
0     1     2     3      4      5     6     7     8      9      0
1     0     1     2      3      4     5     6     7      8      9
结果是:

      C0     C1
0  12345  67890
1  01234  56789

欢迎你,乔丹。请提供一个示例,您希望如何处理这些值?总和连接列表?值连接有一种方法可以做到这一点,但忽略第一列,使其保持不连接,并从第2列开始将第一列移动到索引中,然后运行相同的命令。@ScottBoston解释代码的作用