【问题标题】:How can I groupby in pandas python but conserving the order of the dataframe?如何在 pandas python 中进行分组但保留数据框的顺序?
【发布时间】:2019-07-19 17:27:48
【问题描述】:

我有一个带有下一个属性的数据框 df(其中一个是作为字符串的 Datetime 属性):

+-------------+---------+-------+
| Date        |  Atr1   |  Atr2 |
+-------------+---------+-------+
| '1/1/2015'  |  'A'    |   'B' |
+-------------+---------+-------+
| '1/1/2015'  |  'B'    |   'H' |
+-------------+---------+-------+
| '1/3/2015'  |  'C'    |   'J' |
+-------------+---------+-------+
| '2/3/2015'  |  'D'    |   'L' |
+-------------+---------+-------+

我有按 Date 对象排序的数据框,但随后,我按日期时间分组,并为每组生成一个数据框,如下所示:

dates = df.groupby('Date')

dict_fechas_df = {}

for f in fechas:
    fecha = f[0]
    dict_fechas_df[fecha] = fecha

但是当检查字典的键时,日期显得杂乱无章。那么我怎样才能得到有序的字典呢?

【问题讨论】:

    标签: python pandas sorting dictionary


    【解决方案1】:

    将参数sort=False添加到groupby

    dates = df.groupby('Date', sort=False)
    

    字典的替代解决方案:

    dict_fechas_df = dict(tuple(dates))
    

    但是如果想要字典中的键顺序,需要python3.6+,下面OrderDict,检查this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-17
      • 2019-04-19
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      • 2018-11-22
      • 1970-01-01
      • 2021-03-27
      相关资源
      最近更新 更多