Python – pandas操作之shift位移操作

一、方法参数

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

数据如下: 

Python - pandas操作之shift位移操作

2.shift操作

2.1.periods

df1 = df_head.shift() # 默认移位1
df2 = df_head.shift(periods=2) # 移位2
Python - pandas操作之shift位移操作

2.2.指定axis,操作列

df3 = df_head.shift(axis=1, periods=1)
Python - pandas操作之shift位移操作

2.3.为以后填充空值

# 移位2,并填充空值
df4 = df_head.shift(periods=2, fill_value=0) 
Python - pandas操作之shift位移操作

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

本文从CSDN(点击查看原文)转载而来。不代表烟海拾贝立场,如若转载,请注明出处:https://somirror.com/4786.html

(0)
上一篇 2023-02-07 16:20
下一篇 2023-02-07 16:57

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注