Search code examples
pythonpandaspivot-tabledata-handling

Pivot table error "Can't assign to operator"


I get this error when running the code below 'Can't assign to operator'

df_2 = pd.pivot_table(df, index = df.columns[~df.columns.str.startswith('A')],
                         values = df.columns[ df.columns.str.startswith('A')])

I want to aggregate on all columns that doesn't start with A, and write all data in columns that do start with A following the advise from here:

How to groupby and pivot a dataframe with non-numeric values

Any help will be greatly appreciated.


Solution

  • I think that there are some problem when you assign index and values. I did a mcve and the following code is working in my case

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame(np.random.randn(6,4),
                      columns=["A1", "A2","B1", "B2"])
    
    cols_index = list(df.columns[~df.columns.str.startswith('A')])
    cols_values = list(df.columns[ df.columns.str.startswith('A')])
    
    pd.pivot_table(df, index=cols_index, values=cols_values)
    

    In case for your df this doesn't work try to add a sample of your data.