python - Pandas:根据数据框的逻辑添加列
问题描述
我有一个看起来像这样的数据框
A B C
0 20200608 20200507 202006
1 20200608 20200630 202006
2 20200608 20200701 202006
3 20200508 20200401 202005
4 20200508 20200507 202005
5 20200508 20200508 202005
6 20200408 20203030 202004
7 20200308 20200601 202003
我有一个函数 get_previous_month(202006) -> 202005
如果 B 中的日期 > YYYYMM -1 的 A 中的日期,我想更新我的数据框以在“D”中添加一个布尔值
A 列中的所有日期,对于 C 中相同的 YYYYMM,将是相同的
例如:在第 0 行,C 列是 202006,之前的 YYYYMM 是 202005。20200507 不大于 20200508
A B C D
0 20200608 20200507 202006 False
1 20200608 20200630 202006 True
2 20200608 20200701 202006 True
3 20200508 20200401 202005 False
4 20200508 20200507 202005 True
5 20200508 20200508 202005 True
6 20200408 20203030 202004 True
7 20200308 20200601 202003 Null
解决方案
这就是我所拥有的...
is_current = {}
cutoff = lambda x: pd.unique(df[df['C'] == add_months(x, -1) ]['A']).tolist()
for i, row in df.iterrows():
row_cutoff = cutoff(row['C'])
if row_cutoff:
is_current[i] = int(row['B']) > int(row_cutoff[0])
else:
is_current[i] = None
is_current = [is_current.get(a) for a in range(len(is_current.keys()))]
df['D'] = is_current
df.reset_index(drop=True)
推荐阅读
- c - C 宏扩展未按预期工作 - 低于错误 main.c:11:19: 错误: '(' 标记之前的预期标识符
- python-3.x - 每次启动多处理时进程消耗更多内存
- python - 将两个排序后的数组组合成一个长度相同的新数组
- android - 未能安装以下 Android SDK 软件包,因为某些许可证尚未被接受。29号平台
- flutter - Flutter Share.sharefiles() 没有那个文件或目录,null,null,null
- c++ - 从另一行开始的 .txt 文件中读取文本
- django - 如何在 python 模块中使 datetime 可调用?
- linux - 如何在命令行中选择具有特定模式的文件?
- javascript - 构造非结构文本文件的正则表达式
- hadoop - 为什么reduce输入记录大于map输出记录?