Python Pandas dataframe.pct

您所在的位置:网站首页 chg什么意思中文翻译 Python Pandas dataframe.pct

Python Pandas dataframe.pct

2024-07-12 18:04| 来源: 网络整理| 查看: 265

Python是进行数据分析的一种出色语言,主要是因为以数据为中心的python软件包具有奇妙的生态系统。 Pandas是其中的一种,使导入和分析数据更加容易。

Pandas dataframe.pct_change()函数计算当前元素与先前元素之间的百分比变化。默认情况下,此函数计算前一行的百分比变化。

注意:此函数在时间序列数据中最有用。

用法: DataFrame.pct_change(periods=1, fill_method=’pad’, limit=None, freq=None, **kwargs)

参数: periods:形成百分比变化所需的时间。 fill_method:在计算百分比变化之前如何处理资产净值。 limit:停止前要填充的连续NA数 freq:时间序列API中使用的增量(例如“ M”或BDay())。 **kwargs:其他关键字参数将传递到DataFrame.shift或Series.shift中。

返回:与调用对象的类型相同。

范例1:采用pct_change()函数以查找时间序列数据中的百分比变化。

# importing pandas as pd import pandas as pd    # Creating the time-series index ind = pd.date_range('01/01/2000', periods = 6, freq ='W')    # Creating the dataframe  df = pd.DataFrame({"A":[14, 4, 5, 4, 1, 55],                    "B":[5, 2, 54, 3, 2, 32],                     "C":[20, 20, 7, 21, 8, 5],                    "D":[14, 3, 6, 2, 6, 4]}, index = ind)    # Print the dataframe df

让我们使用dataframe.pct_change()函数以查找数据中的百分比变化。

# find the percentage change with the previous row df.pct_change()

输出: 第一行包含NaN值,因为没有上一行可以从中计算更改。

范例2:采用pct_change()函数来查找还具有NaN值。

# importing pandas as pd import pandas as pd    # Creating the time-series index ind = pd.date_range('01/01/2000', periods = 6, freq ='W')    # Creating the dataframe  df = pd.DataFrame({"A":[14, 4, 5, 4, 1, 55],                    "B":[5, 2, None, 3, 2, 32],                     "C":[20, 20, 7, 21, 8, None],                    "D":[14, None, 6, 2, 6, 4]}, index = ind)    # apply the pct_change() method # we use the forward fill method to # fill the missing values in the dataframe df.pct_change(fill_method ='ffill')

输出:

第一行包含NaN值,因为没有上一行可以从中计算更改。所有NaN DataFrame 中的值已使用填充ffill方法。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3