python - 使用移位函数比较行值
问题描述
我正在学习熊猫,我遇到了以下方法来比较数据框中的行。
在这里,我使用np.were
andshift()
函数来比较列中的值。
import pandas as pd
import numpy as np
# Initialise data to Dicts of series.
d = {'col' : pd.Series([10, 30, 20, 40, 70, 60])}
# creates Dataframe.
df = pd.DataFrame(d)
df['Relation'] = np.where(df['col'] > df['col'].shift(), "Grater", "Less")
df
这里的输出如下所示:
col Relation
0 10 Less
1 30 Grater
2 20 Less
3 40 Grater
4 70 Grater
5 60 Less
我对第 3 行感到困惑,为什么它显示为Grater
?, 40 小于 70,所以它应该显示为Less
. 我在这里做错了什么?
解决方案
因为与 比较40
,20
因为将索引移位1
:
df['Relation'] = np.where(df['col'] > df['col'].shift(), "Grater", "Less")
df['shifted'] = df['col'].shift()
df['m'] = df['col'] > df['col'].shift()
print (df)
col Relation shifted m
0 10 Less NaN False
1 30 Grater 10.0 True
2 20 Less 30.0 False
3 40 Grater 20.0 True <- here
4 70 Grater 40.0 True
5 60 Less 70.0 False
也许你想换班-1
:
df['Relation'] = np.where(df['col'] > df['col'].shift(-1), "Grater", "Less")
df['shifted'] = df['col'].shift(-1)
df['m'] = df['col'] > df['col'].shift(-1)
print (df)
col Relation shifted m
0 10 Less 30.0 False
1 30 Grater 20.0 True
2 20 Less 40.0 False
3 40 Less 70.0 False
4 70 Grater 60.0 True
5 60 Less NaN False
推荐阅读
- git - 如何让 Visual Studio Code 在提交之前保存文件中的更改?
- android - 将项目更新到 android studio 中的 android x 库后,我的 android 程序中收到警告
- r - R data.table 列的累积总和
- javascript - 如何在使用 jQuery 动态更改选项 ID 的选择中定位选项
- sml - 关于如何在 ML 中编写函数 allLessThan 的问题?
- environment-variables - 为什么我无法在 Windows 中编辑或创建系统变量?
- java - Intellij - 在不同的窗口中调试多个 Maven 项目
- javascript - 我想以以下格式动态添加数组中的元素
- regex - 用于验证的正则表达式格式
- powershell - 创建具有不同颜色的多条线的最佳方法