Python - pandas操作之shift位移操作

目录

一、方法参数

二、使用方法

1.读入数据

 2.shift操作

2.1.periods

 2.2.指定axis,操作列

 2.3.为以后填充空值


一、方法参数

DataFrame.shift(periods, frep, axis, fill_value)

periods:要移动的值
frep:拓展索引,值不变
axis:指定要移位的行或列,0为行,1为列
fill_value:指定移位后的填充值,fill_value=0,即表示移位后缺失值填充为0

二、使用方法

1.读入数据

import pandas as pd
df = pd.read_csv('/data/demo.csv')
df_head = df.head().drop(columns=['Gender'])
df_head

数据如下: 

 2.shift操作

2.1.periods

df1 = df_head.shift() # 默认移位1
df2 = df_head.shift(periods=2) # 移位2

 2.2.指定axis,操作列

df3 = df_head.shift(axis=1, periods=1)

 

 2.3.为以后填充空值

# 移位2,并填充空值
df4 = df_head.shift(periods=2, fill_value=0) 

 

位移操作可以针对一些计算,如计算该阶段与下一阶段的比值

猜你喜欢

转载自blog.csdn.net/qq_24256877/article/details/109238036
今日推荐