python - Pandas 将组中的最后一项替换为 if NaN 与另一列

标签 python pandas time-series pandas-groupby

仅当它为空时,我才尝试用另一列的值替换组中的最后一行。我能够分别完成这两部分,但似乎无法将它们结合起来。谁有想法?
这些是单独的部分:

# replace any NaN values with values from 'target'
df.loc[df['target'].isnull(),'target'] = df['value']

# replace last value in groupby with value from 'target'
df.loc[df.groupby('id').tail(1).index,'target'] = df['value']
原始数据:
    date        id      value       target
0   2020-08-07  id01    0.100775    NaN
1   2020-08-08  id01    0.215885    0.215885
2   2020-08-09  id01    0.012154    0.012154
3   2020-08-10  id01    0.374503    NaN
4   2020-08-07  id02    0.369707    0.369707
5   2020-08-08  id02    0.676743    0.676743
6   2020-08-09  id02    0.659521    0.659521
7   2020-08-10  id02    0.799071    NaN
将 groupby('id') 中最后一行的 'target' 列替换为 'value' 中的内容:
    date        id      value       target
0   2020-08-07  id01    0.100775    NaN
1   2020-08-08  id01    0.215885    0.215885
2   2020-08-09  id01    0.012154    0.012154
3   2020-08-10  id01    0.374503    0.374503
4   2020-08-07  id02    0.369707    0.369707
5   2020-08-08  id02    0.676743    0.676743
6   2020-08-09  id02    0.659521    0.659521
7   2020-08-10  id02    0.799071    0.799071

最佳答案

这个应该可以。添加了 tail变量只是为了更容易阅读语法是:

tail = df.groupby('id').tail(1)
df.loc[tail.index,'target'] = df.loc[tail.index]['target'].fillna(tail.value) 
输出:
0 idx        date    id     value    target
1   0  2020-08-07  id01  0.100775       NaN
2   1  2020-08-08  id01  0.215885  0.215885
3   2  2020-08-09  id01  0.012154  0.012154
4   3  2020-08-10  id01  0.374503  0.374503
5   4  2020-08-07  id02  0.369707  0.369707
6   5  2020-08-08  id02  0.676743  0.676743
7   6  2020-08-09  id02  0.659521  0.659521
8   7  2020-08-10  id02  0.799071  0.799071

关于python - Pandas 将组中的最后一项替换为 if NaN 与另一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63273409/

相关文章:

python - Python 中的错误最近邻

r - 高效多时间序列分析的最佳实践

Python - 从 QlineEdit 读取数据并以十六进制字节发送到串行?

python - GTK3 ComboBox 显示 TreeStore 中的父项

python - 如何使用python一条一条地获取tcp消息

python - 区分类层次结构内部和外部的调用者

python - 使用前一列的聚合创建列 - 基于条件

python - 使用条件将列表的 pandas 列拆分为多列。

python - 无法使用 read_excel 从 pandas 中的 xlsx 文件读取日期列?

sql - 使用sql识别具有特定特征的时期