python - 添加列并选择总和最大的列

标签 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() 但这不起作用。我还认为可能有比我正在做的逐步尝试更快的方法来做到这一点。

最佳答案

您可以在 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

关于python - 添加列并选择总和最大的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31165547/

相关文章:

python - Pandas:将数据从列添加到另一个数据帧,直到特定时间结束

python - 如何扩展 python 模块以包含额外的功能? (sqlite3)

python - ValueError : could not broadcast input array from shape (300, 300,3) 变成形状 (300,300)

python - 如何使用 mrjob 迭代处理一个目录下的所有文件

java - 为什么在 Java 1.8 中这样排序

python - 单词和表情符号计数器

python - 使用 cPickle 仅返回文件中的第一个条目

PHP/SQL 数组访问错误

arrays - 在Excel中如何在排序后获取原始行索引

python - 在 2D numpy 数组中查找和删除回文行