我有一个数据框,如:
foo bar qux
0 a 1 3.14
1 b 3 2.72
2 c 2 1.62
3 d 9 1.41
4 e 3 0.58
Run Code Online (Sandbox Code Playgroud)
我想在数据帧的末尾添加一个"总"行:
foo bar qux
0 a 1 3.14
1 b 3 2.72
2 c 2 1.62
3 d 9 1.41
4 e 3 0.58
5 tot 15 9.47
Run Code Online (Sandbox Code Playgroud)
我已经尝试使用该sum
命令,但我最终得到了一个系列,虽然我可以转换回Dataframe,但不维护数据类型:
tot_row = pd.DataFrame(df.sum()).T
tot_row['foo'] = 'tot'
tot_row.dtypes:
foo object
bar object
qux object
Run Code Online (Sandbox Code Playgroud)
我想维护原始数据框中的数据类型,因为我需要将其他操作应用于总行,例如:
baz = 2*tot_row['qux'] + 3*tot_row['bar']
Run Code Online (Sandbox Code Playgroud)
Pou*_*del 34
要同时获得行和列总数:
import numpy as np
import pandas as pd
df = pd.DataFrame({'a': [10,20],'b':[100,200],'c': ['a','b']})
df.loc['Column_Total']= df.sum(numeric_only=True, axis=0)
df.loc[:,'Row_Total'] = df.sum(numeric_only=True, axis=1)
print(df)
a b c Row_Total
0 10.0 100.0 a 110.0
1 20.0 200.0 b 220.0
Column_Total 30.0 300.0 NaN 330.0
Run Code Online (Sandbox Code Playgroud)
jmz*_*jmz 33
附加一个总计行
df.append(df.sum(numeric_only=True), ignore_index=True)
Run Code Online (Sandbox Code Playgroud)
仅当您有一列字符串或对象时才需要进行转换.
这是一个脆弱的解决方案,所以我建议坚持数据框架上的操作.例如.
baz = 2*df['qux'].sum() + 3*df['bar'].sum()
Run Code Online (Sandbox Code Playgroud)
Mat*_*uer 14
df.loc["Total"] = df.sum()
Run Code Online (Sandbox Code Playgroud)
为我工作,我发现它更容易记住。我想念什么吗?可能在早期版本中是不可能的。
我实际上只是想暂时添加总行。永久添加它可以很好地显示,但使以后的计算变得麻烦。
刚发现
df.append(df.sum().rename('Total'))
Run Code Online (Sandbox Code Playgroud)
这会在Jupyter笔记本中打印出我想要的内容,并且看起来不影响df本身。
tsv*_*kas 10
只需使用
df.style.concat(df.agg(['sum']).style)
Run Code Online (Sandbox Code Playgroud)
寻求一种不会更改数据框的解决方案,即使索引中有“总和”也可以工作,并且可以设置样式!
在 pandas 1.5.0 中,一个名为的新方法.style.concat()
使您能够同时显示多个数据帧。这是显示总数(或任何其他统计数据)的好方法,因为它不会更改原始数据帧,并且即使原始数据帧中有名为“sum”的索引也可以工作。
例如:
df.style.concat(df.agg(['sum']).style)
Run Code Online (Sandbox Code Playgroud)
它将返回一个在 jupyter 中可见的格式化表,如下所示:
使用更长的代码,您甚至可以使最后一行看起来有所不同:
import pandas as pd
df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C'])
df.style.concat(df.agg(['sum']).style)
Run Code Online (Sandbox Code Playgroud)
要得到:
请参阅文档中的其他样式设置方法(例如粗体字体或表格线)
小智 9
使用DataFrame.pivot_table
有margins=True
:
import pandas as pd
data = [('a',1,3.14),('b',3,2.72),('c',2,1.62),('d',9,1.41),('e',3,.58)]
df = pd.DataFrame(data, columns=('foo', 'bar', 'qux'))
Run Code Online (Sandbox Code Playgroud)
原文df
:
foo bar qux
0 a 1 3.14
1 b 3 2.72
2 c 2 1.62
3 d 9 1.41
4 e 3 0.58
Run Code Online (Sandbox Code Playgroud)
由于pivot_table
需要某种分组(没有index
参数,它会引发一个ValueError: No group keys passed!
),而你的原始索引是空的,我们将使用该foo
列:
df.pivot_table(index='foo',
margins=True,
margins_name='total', # defaults to 'All'
aggfunc=sum)
Run Code Online (Sandbox Code Playgroud)
瞧!
bar qux
foo
a 1 3.14
b 3 2.72
c 2 1.62
d 9 1.41
e 3 0.58
total 18 9.47
Run Code Online (Sandbox Code Playgroud)
小智 6
替代方式(在Pandas 0.18.1上验证):
import numpy as np
total = df.apply(np.sum)
total['foo'] = 'tot'
df.append(pd.DataFrame(total.values, index=total.keys()).T, ignore_index=True)
Run Code Online (Sandbox Code Playgroud)
结果:
foo bar qux
0 a 1 3.14
1 b 3 2.72
2 c 2 1.62
3 d 9 1.41
4 e 3 0.58
5 tot 18 9.47
Run Code Online (Sandbox Code Playgroud)
小智 6
这就是我的做法,通过转置并使用 allocate 方法与 lambda 函数相结合。这对我来说很简单。
df.T.assign(GrandTotal = lambda x: x.sum(axis=1)).T
Run Code Online (Sandbox Code Playgroud)
以 JMZ 答案为基础
df.append(df.sum(numeric_only=True), ignore_index=True)
Run Code Online (Sandbox Code Playgroud)
如果您想继续使用当前索引,您可以使用 .rename() 命名总和系列,如下所示:
df.append(df.sum().rename('Total'))
Run Code Online (Sandbox Code Playgroud)
这将在表格底部添加一行。
基于马蒂亚斯考尔的回答。
添加行总计:
df.loc["Row_Total"] = df.sum()
Run Code Online (Sandbox Code Playgroud)
要添加列总计,
df.loc[:,"Column_Total"] = df.sum(axis=1)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
56713 次 |
最近记录: |