Pandas: `item` has been deprecated

前端 未结 5 1472
情书的邮戳
情书的邮戳 2020-12-17 14:50

So far I used this line of code here:

max_total_gross = event_data[\"max_total_gross\"].loc[event_data[\"event_id\"] == event_id].item()

Si

相关标签:
5条回答
  • 2020-12-17 15:18

    The method item() is still useful if you want to assert that the Series has length exactly 1, and also get that single value at the same time. I recommend replacing:

    result = ser.item()
    

    with:

    result = ser.values.item()
    

    which should do what you want.

    0 讨论(0)
  • 2020-12-17 15:19

    You could also just use .iloc[0], but keep in mind that it will raise an IndexError if there is not at least one item in the series you're calling it on.

    s = event_data.loc[event_data.event_id == event_id, 'max_total_gross']
    s.iloc[0]
    
    0 讨论(0)
  • 2020-12-17 15:21

    It has been undeprecated again in pandas 1.0 for exactly this use case:

    Series.item() and Index.item() have been undeprecated (GH29250)

    from https://pandas.pydata.org/docs/whatsnew/v1.0.0.html#deprecations. See also discussion in the issue GH29250.

    So consider updating or ignoring or silencing the warning instead.

    0 讨论(0)
  • 2020-12-17 15:23

    If need first matched value use iter with next, advantage is if no value is matched is returned default value:

    s = event_data.loc[event_data.event_id == event_id, 'max_total_gross']
    
    out = next(iter(s), 'no match')
    print (out)
    
    0 讨论(0)
  • 2020-12-17 15:38

    I just went through the same problem. The quickest way for me to solve the item() depreciation was to use the .iloc[0]

    0 讨论(0)
提交回复
热议问题