python-2.7 - Pandas 在一列上分组,另一列上的最大日期python

标签 python-2.7 pandas

我有一个包含以下数据的数据框:

invoice_no  dealer  billing_change_previous_month        date
       110       1                              0  2016-12-31
       100       1                         -41981  2017-01-30
      5505       2                              0  2017-01-30
      5635       2                          58730  2016-12-31

我只想拥有一个最大日期的经销商。所需的输出应该是这样的:
invoice_no  dealer  billing_change_previous_month        date
       100       1                         -41981  2017-01-30
      5505       2                              0  2017-01-30

每个经销商应与最大日期不同,
在此先感谢您的帮助。

最佳答案

您可以使用 groupby 和 transform 使用 bool 索引

df_new = df[df.groupby('dealer').date.transform('max') == df['date']]

    invoice_no  dealer  billing_change_previous_month   date
1   100         1       -41981                          2017-01-30
2   5505        2       0                               2017-01-30
即使有两个以上的经销商,该解决方案也能按预期工作(解决 Ben Smith 发布的问题),
df = pd.DataFrame({'invoice_no':[110,100,5505,5635,10000,10001], 'dealer':[1,1,2,2,3,3],'billing_change_previous_month':[0,-41981,0,58730,9000,100], 'date':['2016-12-31','2017-01-30','2017-01-30','2016-12-31', '2019-12-31', '2020-01-31']})

df['date'] = pd.to_datetime(df['date'])
df[df.groupby('dealer').date.transform('max') == df['date']]


    invoice_no  dealer  billing_change_previous_month   date
1   100         1       -41981                          2017-01-30
2   5505        2       0                               2017-01-30
5   10001       3       100                             2020-01-31

关于python-2.7 - Pandas 在一列上分组,另一列上的最大日期python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48754049/

相关文章:

django - 如何修复我的 Django ImproperlyConfigured 异常?

python - 在循环中恢复循环的Pythonic方法是什么

macos - 如何暂停/恢复 Python 脚本?

python - 用 python 填充 excel 文件搞乱了我的日期

python - 如何对我的 DataFrame 中的值进行分组和计数?

python - pandas DataFrame - 如何对行进行分组和标记

Python 64位SciPy安装错误

python - 读取 excel 文件时出现 Pandas 和 xlrd 错误

python - python中的文本语言检测

Python性能调优: JSON to CSV,大文件