多列的数据框列表

cra*_*WAI 2 python list dataframe pandas

如何'bar4': [[5,1,11],[6,2,22],[5,3,33]]在以下数据框中添加包含当前列列表的新列。

import pandas as pd

foo1 = (['L1','L1','L2'])
foo2 = ([5,5,6])
foo3 = ([1,1,2])

index = pd.MultiIndex.from_arrays(
    [foo1,foo2,foo3], names=['ifoo1','ifoo2','ifoo3']
    )
init = pd.DataFrame({
    'bar1': [5,6,5],
    'bar2': [1,2,3],
    'bar3': [11,22,33]
    }, index=index)
Run Code Online (Sandbox Code Playgroud)

我最初认为这将是与 something 类似的操作init['barX'] = init.bar1 + init.bar2,但int['bar4'] = init.bar1, init.bar2, init.bar3绝对不是解决方案。

想要的结果:

 #                 bar1  bar2 bar3 bar4
 # foo1 foo2 foo3
 # L1   5    1      5    1    11   [5,1,11]
 # L1   5    1      6    2    22   [6,2,22]
 # L2   6    2      5    3    33   [5,3,33]
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

我想你需要值转换为numpy array通过values使用numpy.ndarray.tolist

init['bar4'] = init.values.tolist()
print (init)
                   bar1  bar2  bar3        bar4
ifoo1 ifoo2 ifoo3                              
L1    5     1         5     1    11  [5, 1, 11]
            1         6     2    22  [6, 2, 22]
L2    6     2         5     3    33  [5, 3, 33]
Run Code Online (Sandbox Code Playgroud)

如果需要指定列:

cols = ['bar1','bar2','bar3']
init['bar4'] = init[cols].values.tolist()
print (init)
                   bar1  bar2  bar3        bar4
ifoo1 ifoo2 ifoo3                              
L1    5     1         5     1    11  [5, 1, 11]
            1         6     2    22  [6, 2, 22]
L2    6     2         5     3    33  [5, 3, 33]
Run Code Online (Sandbox Code Playgroud)