添加列并选择具有最大总和的列

时间:2015-07-01 15:25:51

标签: python sorting pandas sum dataframe

我希望对数据框进行排序。我有这个数据框:

Y    X1  X2  X3
Y1   1   0   1
Y2   1   0   0
Y3   1   0   0
Y4   0   1   0

有很多专栏。如果您添加了列,我想选择具有最大总和的X值。

我一直试图通过添加一行来实现这一点:

Y    X1  X2  X3
Y1   1   0   1
Y2   1   0   0
Y3   1   0   0
Y4   0   1   1
sum  3   1   2

然后我会用总和行

对它进行排序
Y    X1  X3  X2
Y1   1   1   0
Y2   1   0   0
Y3   1   0   0
Y4   0   1   1
sum  3   2   1

并选择要使用的30列。但是,我只能得到这样的行的总和:

Y    X1  X3  X2  sum
Y1   1   1   0    2
Y2   1   0   0    1
Y3   1   0   0    1
Y4   0   1   1    2

使用

pivot_table['sum'] = pivot_table.sum(axis=1)

我也试过

pivot_table['sum'] = pivot_table.sum(axis=0)

并尝试添加.transpose(),但这不起作用。我也认为有可能比我正在逐步尝试做更快的方法。

3 个答案:

答案 0 :(得分:3)

您可以在df上调用sum,这将返回一个系列,然后您可以对此系列进行排序,然后使用该系列的索引重新排序您的df:

In [249]:
# note that column 'X3' will produce a sum value of 2
t="""Y    X1  X2  X3
Y1   1   0   1
Y2   1   0   1
Y3   1   0   0
Y4   0   1   0"""
# load the data
df = pd.read_csv(io.StringIO(t), sep='\s+', index_col=[0])
df

Out[249]:
    X1  X2  X3
Y             
Y1   1   0   1
Y2   1   0   1
Y3   1   0   0
Y4   0   1   0

sum的结果将返回我们要对其进行排序的系列,并传递参数inplace=False,以便返回副本ascending=False

In [250]:
# now calculate the sum, call sort on the series
s = df.sum().sort(ascending=False, inplace=False)
s
​
Out[250]:
X1    3
X3    2
X2    1
dtype: int64

In [251]:
# now use fancy indexing to reorder the df
df.ix[:,s.index]

Out[251]:
    X1  X3  X2
Y             
Y1   1   1   0
Y2   1   1   0
Y3   1   0   0
Y4   0   0   1

如果您只需要前n列,则可以对索引进行切片:

In [254]:
df = df[s.index[:2]]
df

Out[254]:
    X1  X3
Y         
Y1   1   1
Y2   1   1
Y3   1   0
Y4   0   0

答案 1 :(得分:0)

您可以在数据框上使用describe()来获取每列的统计信息(包括总和)。然后使用带有描述结果的最大总和的列对数据框进行排序。

我想说,向DataFrame添加一个与其他行不同的语义的行通常不是一个好主意。它不是Excel。

答案 2 :(得分:0)

我有一个类似的问题,我只想让列的总数最大。这是我的解决方案:

ncols是要保留多少列

def top_cols(dftemp,ncols):
    dfsum = dftemp.sum().to_frame().reset_index()
    dfsum = dfsum.sort_values(by=0,ascending=False, inplace=False).head(ncols)
    top_cols = dfsum['index'].tolist()
    return dftemp[top_cols]

df = top_cols(df,50) #this would return the dataframe with the 50 columns with the largest sums