【发布时间】:2020-05-21 06:20:34
【问题描述】:
我正在执行大量数据清理,并希望跟踪我操作过的行。有没有一种优雅的方式来跟踪我所做的更改 (最好在数据框的一列内)?
我的初始数据框的一个示例是:
import numpy as np
import pandas as pd
ind = pd.Index([pd.Timestamp('2019-03-17'),
pd.Timestamp('2019-03-18'),
pd.Timestamp('2019-03-20'),
pd.Timestamp('2019-03-21'),
pd.Timestamp('2019-03-22'),
pd.Timestamp('2019-03-24')])
data = {'col':[25,25,24,3,25,24]}
df = pd.DataFrame(data, ind)
col
2019-03-17 25
2019-03-18 25
2019-03-20 24
2019-03-21 3
2019-03-22 25
2019-03-24 24
我正在执行几个清理操作(我将它们称为“a”和“b”),并且我想在一个新列中标记我已经完成这些操作的行。
# operation a: create full date range and forward fill the missing days
df = df.asfreq(freq='D', fill_value=np.nan)
df['col'].fillna(method='ffill', inplace=True)
# operation b: check for rate changes larger than a particular value and forward fill those rows
df.loc[df['col'].diff()<-3, 'col'] = np.nan
df['col'].fillna(method='ffill', inplace=True)
我想添加一个列来跟踪我在哪些行上执行了这些操作,这样输出看起来像这样:
col changed
2019-03-17 25.0 0
2019-03-18 25.0 0
2019-03-19 25.0 a
2019-03-20 24.0 0
2019-03-21 24.0 b
2019-03-22 25.0 0
2019-03-23 25.0 a
2019-03-24 24.0 0
我想到的最佳方法是在每一步创建“影子”dfs,并比较之前(“影子”)和之后(新 df)的值,然后修改“更改”列,如果有区别,但这感觉很笨拙。有没有更简洁的方法来做到这一点?
谢谢!
【问题讨论】:
标签: python pandas dataframe missing-data data-cleaning