我的数据框可以像这样复制:
import pandas as pd
link = 'https://raw.githubusercontent.com/timothylombard/RSB/master/RSBdata.csv'
df = pd.read_csv(link)
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
我想做什么
然后,我想比较和报告更改行之间和更改行之前列值的差异。看图片,我想比较2018年1月13日与2017年10月10日建立索引的数据
到目前为止,我已经可以使用.shift添加新列
df['PriorConnections'] = df['Connections'].shift()
然后添加另一列具有不同值的列,如:
df['Connections_Diff'] = df['Connections'] - df['PriorConnections']
我还可以使用-
来标识更改行cr = df.loc[df.Connections_Diff > 0]
df.loc[cr]
如何找到df.loc [cr]之前的行?
答案 0 :(得分:2)
您可以这样检查吗?
>> df = pd.DataFrame({'Col1': [10, 20, 10, 15, 15],
'Col2': [13, 23, 18, 33, 48],
'Col3': [17, 27, 22, 37, 52]})
>> series_to_check = df['Col1']
>> [(i, i-1) for i in range(1,len(series_to_check)-1) if series_to_check[i]!=series_to_check[i-1] ]
>> [(1, 0), (2, 1), (3, 2)]
>> # returns a list of tuples [(`changed_row_index`, `previous_row_index`)]
它实质上检查了系列中的每个项目及其先前的数据。
答案 1 :(得分:1)
您可以创建一个包含changed_rows的所有索引的列表。
因此,您可以这样做:
list_changed_rows = []
for i in range(1, df.shape[0]):
if df.iloc[i,2] != df.iloc[i-1,2]:
list_changed_rows.append(i)
要分析它们,您可以执行以下操作:
for i in list_changed_rows:
row_before = df.iloc[[i-1]]
row_changed = df.iloc[[i]]
# code