3

I have an empty DataFrame with columns but no rows. I want to apply groupby on it but it results in no columns. How to apply groupby and keep columns?

df = pd.DataFrame(data={'a':[], 'b': []})
df = df.groupby('a').apply(lambda g: g).reset_index(drop=True)

output:

Empty DataFrame
Columns: []
Index: []

df.index

Float64Index([], dtype='float64', name='a')
Dariusz Krynicki
  • 2,544
  • 1
  • 22
  • 47
  • what is dk ? and why you need apply function to empty dataframe ? – BENY Nov 29 '19 at 15:48
  • I realize I can make some logic to check if df is empty but I want to avoid it for a reason. I am after why I loose columns here? – Dariusz Krynicki Nov 29 '19 at 15:55
  • related : https://stackoverflow.com/questions/46090386/keep-columns-after-a-groupby-in-an-empty-dataframe – anky Nov 29 '19 at 16:13
  • @anky_91 I think the answer there covers this question. Voting as duplicate. – r.ook Nov 29 '19 at 17:03
  • 1
    @r.ook no, the question in the URL provided remains unanswered as the extra argument does not solve the problem. I read that question before I submitted my question here. Ty that solution and see if it works if you think it answers the question I asked. – Dariusz Krynicki Nov 30 '19 at 11:08

1 Answers1

1

For pandas 1.1.0 please use

df.groupby('a', as_index=False).aggregate(lambda g: g) 

output:

Empty DataFrame
Columns: [a, b]
Index: []
Grzegorz
  • 1,268
  • 11
  • 11