【问题标题】:Sorting Dask dataframe with two fields使用两个字段对 Dask 数据帧进行排序
【发布时间】:2021-06-24 19:15:30
【问题描述】:

在此示例中,我尝试使用从 date 字段中提取的 balanceyear 两列对 Dask 数据帧进行排序。我正在尝试将余额作为字符串与年份作为字符串连接到一个新字段中,但出现错误:

pdf = pd.DataFrame({
    'id': [1, 1, 1, 2, 2],
    'balance': [350, 340, 130, 280, 260],
    'date' : [datetime(2021,3,1), datetime(2021,2,7), datetime(2021,7,1),
              datetime(2021,2,6), datetime(2021,3,18)]
})

ddf = dd.from_pandas(pdf, npartitions=100) 

ddf['newIndex'] = str(ddf['balance']) + (ddf['date']).year   # <-- this throws the error

ddf = ddf.set_index(['newIndex'])

我得到的错误是:

AttributeError: 'Series' 对象没有属性 'year'

日期字段是一个系列,我明白了,但是如何从日期中提取年份并连接余额以按此新字段排序?

【问题讨论】:

    标签: python python-3.x pandas dask


    【解决方案1】:

    稍作调整即可完成这项工作:

    ddf['newIndex'] = ddf['balance'].astype('str')+ ddf['date'].dt.year.astype('str')
    

    请注意,主要错误是缺少 .dt 方法,稍后您将希望将两列都添加为 str 来添加它们。

    但是,就您要实现的目标而言,最好先按年份对数据进行分区,然后在分区内进行排序。这当然取决于您的数据的具体情况。

    【讨论】:

      猜你喜欢
      • 2011-09-02
      • 2017-03-08
      • 1970-01-01
      • 2017-09-13
      • 2017-06-30
      • 2011-06-12
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      相关资源
      最近更新 更多