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:
我期待编写一个快速脚本,它将运行带有两列的csv文件,并为我提供行B,其中B列中的值从一个值切换到另一个值:
eg:
例如:
dataframe:
数据帧:
# | A | B
--+-----+-----
1 | 2 | 3
2 | 3 | 3
3 | 4 | 4
4 | 5 | 4
5 | 5 | 4
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.
会告诉我第2行和第3行之间发生了变化。我知道如何使用for循环来获取这些值,但我希望有更多的pythonic方法来解决这个问题。
1 个解决方案
#1
12
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
This will your required rows
这将是您所需的行
#1
12
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
This will your required rows
这将是您所需的行