首页 > 解决方案 > 如何跟踪熊猫数据框中已更改的列

问题描述

我正在执行大量数据清理,并希望跟踪我操作过的行。是否有一种优雅的方式来跟踪我所做的更改(最好在数据框的列中)?

我的初始数据框的一个示例是:

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)的值,如果有差异,则修改“更改”列,但这感觉很笨拙。有没有更简洁的方法来做到这一点?

谢谢!

标签: pythonpandasdataframemissing-datadata-cleaning

解决方案


假设 DataFrame 包含一个名为changed并填充了除 之外的值的列np.nan,您可以执行以下操作:

# operation a
df = df.asfreq(freq='D', fill_value=np.nan)
df['col'].fillna(method='ffill', inplace=True)
df['changed'].fillna('a', inplace=True)

# operation b
df.loc[df['col'].diff()<-3, ['col', 'changed']] = [np.nan, 'b']
df['col'].fillna(method='ffill', inplace=True)

推荐阅读