Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas settingwithcopywarning on groupby

Tags:

python

pandas

While I generally understand the warnings, and many posts deal with this, I don understand why I am getting a warning only when I reach the groupby line (the last one):

grouped = data.groupby(['group'])

for name, group in grouped:
    data2=group.loc[data['B-values'] > 0]
    data2["unique_A-values"]=data2.groupby(["A-values"])["A-values"].transform('count')

EDIT: Here is my dataframe (data):

group    A-values    B-values
human    1           -1
human    1            5
human    1            4
human    3            4
human    2           10
bird     7            8
....

For B-values > 0 (data2=group.loc[data['B-values'] > 0]):

human has two A-values equal to one, one equals to 3 and one equals to 2 (data2["unique_A-values"]=data2.groupby(["A-values"])["A-values"].transform('count'))

like image 947
Sara Avatar asked Oct 27 '25 15:10

Sara


1 Answers

You get the error because you take a reference to your groupby and then try add a column to it, so it's just warning you that if your intention is to update the original df then this may or may not work.

If you are just modifying a local copy then take a copy using copy() so it's explicit and the warning will go away:

for name, group in grouped:
    data2=group.loc[data['B-values'] > 0].copy() # <- add .copy() here
    data2["unique_A-values"]=data2.groupby(["A-values"])["A-values"].transform('count')
like image 85
EdChum Avatar answered Oct 30 '25 05:10

EdChum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!