Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/366.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.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_Python 3.x_Pandas - Fatal编程技术网

Python 基于多级索引的熊猫数据帧行添加

Python 基于多级索引的熊猫数据帧行添加,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有一个数据帧,如: (multilevel)index aaa,aaa,aaa,bbb,bbb,bbb,ccc,ccc Column 1, 1 , 1 , 0, 1, 0, 1 , 1 我想根据索引添加行,以便获得: index aaa, bbb, ccc column 3, 1, 2 可能吗 任何帮助都将不胜感激 谢谢也许你可以通过

我有一个数据帧,如:

(multilevel)index  aaa,aaa,aaa,bbb,bbb,bbb,ccc,ccc

    Column          1,  1 , 1 , 0,  1,  0,  1 , 1               
我想根据索引添加行,以便获得:

   index       aaa,    bbb,     ccc 
   column       3,      1,       2        
可能吗

任何帮助都将不胜感激


谢谢

也许你可以通过转置来做类似的事情

import pandas as pd

df = pd.DataFrame([['aaa', 'aaa', 'aaa','bbb', 'bbb', 'bbb', 'ccc', 'ccc'],
                   [1, 1, 1, 0, 1, 0, 1, 1]], index = ['index', 'column'])
因此,我首先进行转置,对它们进行分组,然后再次进行转置:

df = df.T
df = df.groupby('index').sum()
df = df.T
输出:

index   aaa  bbb  ccc
column    3    1    2

如果列具有相同的名称,您可以通过
堆栈
+
透视表
将聚合函数设置为
求和
来获得所需的位置

安装程序 堆叠和枢轴
import pandas as pd
df = pd.DataFrame({'id1': [1,1,1,2], 'id2': [1,2,3,1],
                 '1': [1,1,1,1], '2': [0,0,1,1], '3': [0,1,0,0],
                 '4': [0,0,0,0], '5': [1,1,0,0], '6': [0,1,0,0]})
df = df.set_index(['id1', 'id2'])
df.columns=['aaa','aaa','aaa','bbb','bbb','bbb']

         aaa  aaa  aaa  bbb  bbb  bbb
id1 id2                              
1   1      1    0    0    0    1    0
    2      1    0    1    0    1    1
    3      1    1    0    0    0    0
2   1      1    1    0    0    0    0
stacked = df.stack().reset_index()
df = pd.pivot_table(stacked, index=['id1', 'id2'], columns='level_2', values=0, aggfunc='sum')
df.columns.name=None

print(df)
         aaa  bbb
id1 id2          
1   1      1    1
    2      2    2
    3      2    0
2   1      2    0