Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.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_Dataframe - Fatal编程技术网

Python 从数据帧中删除重复的列索引

Python 从数据帧中删除重复的列索引,python,pandas,dataframe,Python,Pandas,Dataframe,我正在寻找一种解决方案来删除数据帧中的重复列索引-我需要做的是逐行添加重复列中的值,然后只保留这些列中的一列的总和值 df = pd.DataFrame(np.array([[0,0,0,1,0,0,0], [0,1,0,0,0,0,0], [0,0,0,0,0,0,1]]), columns=[1,1,2,2,2,3,3], index=[1,2,3]) 1 1 2 2 2 3 3 1 0 0 0 1 0 0 0

我正在寻找一种解决方案来删除数据帧中的重复列索引-我需要做的是逐行添加重复列中的值,然后只保留这些列中的一列的总和值

df = pd.DataFrame(np.array([[0,0,0,1,0,0,0], [0,1,0,0,0,0,0],
                        [0,0,0,0,0,0,1]]), columns=[1,1,2,2,2,3,3], index=[1,2,3])

   1  1  2  2  2  3  3
1  0  0  0  1  0  0  0
2  0  1  0  0  0  0  0
3  0  0  0  0  0  0  1
应该成为

   1  2  3
1  0  1  0
2  1  0  0
3  0  0  1
你试过了吗

df = df.loc[:,~df.columns.duplicated(keep='last')]

由于缺少数据,您的问题有一个丑陋的尝试:

import pandas as pd
df = pd.DataFrame(np.array([[0,0,0,1,0,0,0], [0,1,0,0,0,0,0], 
                            [0,0,0,0,0,0,1]]))
df.columns = [1,1,2,2,2,3,3]
df1 = df.groupby(lambda x:x, axis=1).sum()
df1.index = range(1,4)
df1

输出您发布的所需数据帧。以下
df1.index=range(1,4)
仅用于重新索引行,因为在您的示例中,行以
1
开头。

仅按列分组:

df.groupby(df.columns, 1).sum()

   1  2  3
1  0  1  0
2  1  0  0
3  0  0  1
或者正如@user2285236所指出的那样

df.groupby(axis=1, level=0).sum()

这里不需要
groupby

df.sum(level=0,axis=1)
Out[358]: 
   1  2  3
1  0  1  0
2  1  0  0
3  0  0  1

您的df中有重复的列名吗?是的-我需要为分类列创建虚拟变量-结果显示,在列之间也有相同的类别-因此复杂度还需要在重复的columnsAh中汇总值!那我的答案就不行了!;)因为我认为他想删除重复的内容,只保留最后发生的内容。如果答案符合你的目的,请随意接受!或者
df.groupby(axis=1,level=0).sum()
Nice!非常简洁。