Home>

I want to handle groupby with multiple columns in python.
I want to create a column called "Average value of target""for samples with the same value in"col1, col2

Error message
TypeError: ("'DataFrame' object is not callable", 'occurred at index date')
Applicable source code

For example, the data is
With df (dataframe)
ix col1 col2 target
0 0 0 0
1 0 1 1
2 0 2 0
3 1 0 1
4 2 1 1
5 2 2 0
There is a thing,
If we try to create a new column called "Average value of target of sample" with the same value in"col1
a = df.groupby ('col1') ['target']. mean ()
df ['new_col'] = df ['col1']. map (a)

Attempting to create a new column called "average of target values" for samples with the same value in "quot1, col1, col2"
a = df.groupby (['col1&apos ;,'col2']) ['target']. mean ()
df ['new_col'] = df [['col1&apos ;,'col2']]. map (a)
If i do not go.

a = df.groupby (['col1', 'col2']) ['target']. mean ()
df ['new_col'] = df [['col1', 'col2']]. map (a)

Thanks for your consideration.

Tried

Please describe what you tried for the problem here.

Supplemental information (FW/tool version etc.)

Please provide more detailed information here.

  • Answer # 1

    Please useDataFrame.groupby (). transform ()

    import pandas as pd
    df = pd.DataFrame ({
        'ix': [0,1,2,3,4,5],
        'col1': [0,0,0,1,2,2],
        'col2': [0,1,2,0,1,2],
        'target': [0,1,0,1,1,0]
    })
    df ['new_col'] = df.groupby (['col1', 'col2']) ['target']. transform ('mean')
    print (df)
    # ix col1 col2 target new_col
    # 0 0 0 0 0 0
    # 1 1 0 1 1 1
    # 2 2 0 2 0 0
    # 3 3 1 0 1 1
    # 4 4 2 1 1 1
    # 5 5 2 2 0 0