python - 如何跟踪熊猫数据框中已更改的列
问题描述
我正在执行大量数据清理,并希望跟踪我操作过的行。是否有一种优雅的方式来跟踪我所做的更改(最好在数据框的列中)?
我的初始数据框的一个示例是:
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)的值,如果有差异,则修改“更改”列,但这感觉很笨拙。有没有更简洁的方法来做到这一点?
谢谢!
解决方案
假设 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)
推荐阅读
- php - 使用 foreach(多维数组)从键中获取值
- c# - 如何在一个表单上创建多个页面而不显示标签页
- python - 按下按钮后如何使图像出现?
- c++ - 在 unordered_set 中存储多态对象
- javascript - HTML按钮没有消失?
- opencv - opencv中RGB图像的色调图
- centos6 - mysql 连接器 32 与 64 位,CentOS 上的 yum 更新
- ios - Swift - 一个月后重置数据
- javascript - XNAT SimpleUploadPlugin - 如何包含 jQuery 插件
- python - 显示 ['and', 'and', 'and', 'and', 'and', 'and'] 而不是实际值