0

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.

rpanai
  • 12,515
  • 2
  • 42
  • 64
nielsen
  • 383
  • 1
  • 6

1 Answers1

1

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.

rpanai
  • 12,515
  • 2
  • 42
  • 64
  • Ok, I now know what you mean by mcve. Thanks for the help. I will try it out. – nielsen Apr 20 '20 at 17:11
  • It gives me the error "TypeError: '<' not supported between instances of 'int' and 'datetime.datetime'" – nielsen Apr 20 '20 at 17:37
  • I understand, but how do I make that if I have 198 columns and 4080 rows? Not sure how I can recreate a dataset different from the one you made. Would it make a difference that some columns have string data, and some data take values NaN? – nielsen Apr 20 '20 at 17:47