确定 pandas 数据框中的列值何时发生变化 [英] Determining when a column value changes in pandas dataframe

查看:17
本文介绍了确定 pandas 数据框中的列值何时发生变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望编写一个快速脚本,该脚本将运行包含两列的 csv 文件,并为我提供 B 列中的值从一个值切换到另一个值的行:

I am looking to write a quick script that will run through a csv file with two columns and provide me the rows in which the values in column B switch from one value to another:

例如:

数据框:

# |  A  |  B  
--+-----+-----
1 |  2  |  3
2 |  3  |  3
3 |  4  |  4
4 |  5  |  4
5 |  5  |  4

告诉我变化发生在第 2 行和第 3 行之间.我知道如何使用 for 循环获取这些值,但我希望有一种更 Python 化的方法来解决这个问题.

would tell me that the change happened between row 2 and row 3. I know how to get these values using for loops but I was hoping there was a more pythonic way of approaching this problem.

推荐答案

您可以为差异创建一个新列

You can create a new column for the difference

> df['C'] = df['B'].diff()
> print df
   #  A  B   C
0  1  2  3 NaN
1  2  3  3   0
2  3  4  4   1
3  4  5  4   0
4  5  5  4   0

> df_filtered = df[df['C'] != 0]
> print df_filtered
   #  A  B  C
2  3  4  4  1

这将是您所需的行

这篇关于确定 pandas 数据框中的列值何时发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆