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

Python 应用程序追加总计行

Python 应用程序追加总计行,python,pandas,Python,Pandas,我已经看过了很多将一行放在数据帧末尾的例子。我只是想知道为什么下面的方法不起作用: import pandas as pd dict = { 'a' : [1,2 ,3, 4, 5], 'b' : [3, 5, 7, 9, 10] } df = pd.DataFrame(dict) # print(df) def func(x): x['sum'] = x.sum() df2 = df.apply(lambda x: func(x), axis=0) print

我已经看过了很多将一行放在数据帧末尾的例子。我只是想知道为什么下面的方法不起作用:

import pandas as pd

dict = {
    'a' : [1,2 ,3, 4, 5],
    'b' : [3, 5, 7, 9, 10]
}

df = pd.DataFrame(dict)
# print(df)

def func(x):
    x['sum'] = x.sum()

df2 = df.apply(lambda x: func(x), axis=0)

print(df2)
在这里,x始终是一个包含完整列的序列,我将附加一个名为sum的索引。请导游


编辑:如果我们可以用axis=1计算sum,为什么不能用axis=0进行计算。

这里缺少
从函数返回x

def func(x):
    x['sum'] = x.sum()
    return x

df2 = df.apply(lambda x: func(x), axis=0)
print(df2)

      a   b
0     1   3
1     2   5
2     3   7
3     4   9
4     5  10
sum  15  34
但最简单的是使用:


非常感谢!我是python新手,还有很多东西需要学习:)
df.loc['sum'] = df.sum()