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
方法。
相關用法
- Python pandas.map()用法及代碼示例
- Python Pandas Series.str.len()用法及代碼示例
- Python Pandas.factorize()用法及代碼示例
- Python Pandas TimedeltaIndex.name用法及代碼示例
- Python Pandas dataframe.ne()用法及代碼示例
- Python Pandas Series.between()用法及代碼示例
- Python Pandas DataFrame.where()用法及代碼示例
- Python Pandas Series.add()用法及代碼示例
- Python Pandas.pivot_table()用法及代碼示例
- Python Pandas Series.mod()用法及代碼示例
- Python Pandas Dataframe.at[ ]用法及代碼示例
- Python Pandas Dataframe.iat[ ]用法及代碼示例
- Python Pandas.pivot()用法及代碼示例
- Python Pandas dataframe.mul()用法及代碼示例
- Python Pandas.melt()用法及代碼示例
注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas dataframe.pct_change()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。