Python的df.cumsum()函数

作者 : admin 本文共1084个字,预计阅读时间需要3分钟 发布时间: 2024-06-10 共2人阅读

Python Pandas dataframe.cumsum()

Python是一种进行数据分析的伟大语言,主要是因为以数据为中心的Python包的奇妙生态系统。Pandas就是这些包中的一个,它使导入和分析数据变得更加容易。

Pandas dataframe.cumsum()用于查找任何axis上的累积和值。每个单元格都被填充了迄今为止所看到的数值的累积和。

语法: DataFrame.cumsum(axis=None, skipna=True, *args, **kwargs)

参数:
axis: {指数(0),列(1)}。
skipna : 排除NA/null值。如果整个行/列是NA,结果将是NA。

示例#1:使用cumsum()函数来查找沿索引axis的数值的累积和。

# importing pandas as pd
import pandas as pd
  
# Creating the dataframe
df = pd.DataFrame({"A":[5, 3, 6, 4],
                   "B":[11, 2, 4, 3],
                   "C":[4, 3, 8, 5],
                   "D":[5, 4, 2, 8]})
  
# Print the dataframe
df

输出 :

Python的df.cumsum()函数插图

现在找出索引axis上数值的累积总和

# To find the cumulative sum
df.cumsum(axis = 0)

输出 :

Python的df.cumsum()函数插图(1)

例子#2:使用cumsum()函数找到迄今为止沿列axis看到的数值的累积和。

# importing pandas as pd
import pandas as pd
  
# Creating the dataframe
df = pd.DataFrame({"A":[5, 3, 6, 4],
                   "B":[11, 2, 4, 3],
                   "C":[4, 3, 8, 5],
                   "D":[5, 4, 2, 8]})
  
# To find the cumulative sum along column axis
df.cumsum(axis = 1)

输出 :

Python的df.cumsum()函数插图(2)

例子#3:使用cumsum()函数,在数据帧中存在NaN值的情况下,找出迄今为止沿索引axis看到的数值的累积和。

# importing pandas as pd
import pandas as pd
  
# Creating the dataframe
df = pd.DataFrame({"A":[5, 3, None, 4],
                   "B":[None, 2, 4, 3],
                   "C":[4, 3, 8, 5],
                   "D":[5, 4, 2, None]})
  
# To find the cumulative sum
df.cumsum(axis = 0, skipna = True)

输出 :

Python的df.cumsum()函数插图(3)

输出是一个数据框架,其中的单元格包含迄今为止沿索引axis看到的数值的累积和。数据框架中的任何一个Nan值都被跳过。

本站无任何商业行为
个人在线分享 » Python的df.cumsum()函数
E-->