【问题标题】:Why does the groupby command in Pandas produce non-exist ids?为什么 Pandas 中的 groupby 命令会产生不存在的 id?
【发布时间】:2022-08-19 18:47:24
【问题描述】:

我在我的数据框上使用 pandas groupby 命令:

df.groupby(\'courier_id\').type_of_vehicle.size()

但是这段代码会产生一些不在我的数据框中的“courier_id”

courier_id
00aecd42-472f-11ec-94e0-77812be296a5    4
011da6a6-eb0b-11ec-97e1-179dc13cdf87    1
0140f63c-02e0-11ed-b314-9b2e7e4f7e5c    1
0188d572-7228-11ec-ab3b-07d470cb404d    7
01cef7ba-e32e-11ec-bb21-67c7079055d4    0
                                       ..
c98fc418-7b51-11ec-a81c-77139d6dd889    0
d98a4b9a-d056-11ec-9e3c-0b80c11ec04b    1
dae54c80-d1f8-11ec-bbb0-b71d7b2c4e1a    1
f7925664-0ac1-11ed-ab40-df16023f78cb    0
f857cb84-371c-11ec-9af6-ffeaeea4b0f1    4
Name: type_of_vehicle, Length: 268, dtype: int64

我检查了它:\'01cef7ba-e32e-11ec-bb21-67c7079055d4\' in df.courier_id.values 结果是 False

我使用了df.groupby(\'courier_id\').get_group(\'01cef7ba-e32e-11ec-bb21-67c7079055d4\'),它引发了 KeyError,但是当在其中生成时,返回空 DataFrame

注意:当我将我的数据框切片为new_df = df[[\'courier_id\', \'type_of_vehicle\']] 时,结果变得正确!

  • 您能否提供一些示例数据来说明您的观察?
  • 不幸的是,我不能

标签: python pandas


【解决方案1】:

如果您提供一些可重现的代码/数据,我们将不胜感激。这样我们就可以为您提供最好的答案。

但是,我认为问题是由于以下原因:

当您使用函数groupby() 时,原来的courier_id 成为转换后的DataFrame 的新索引。尝试使用.reset_index(),您的问题应该得到解决。

df.groupby('courier_id').type_of_vehicle.size().reset_index()

【讨论】:

    猜你喜欢
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 2020-03-24
    • 1970-01-01
    • 2013-12-05
    相关资源
    最近更新 更多