2
import pandas as pd
import collections

df = pd.DataFrame(columns=['a','b','c','d'])
counter = collections.Counter({'a':1, 'b':2})

What I want to do is insert counter to df so that the result would be like this:

          a         b         c         d
0         1         2         0         0

How can I do this?

user3595632
  • 5,380
  • 10
  • 55
  • 111

1 Answers1

6

You can append the counter to the data frame:

df.append(counter, ignore_index=True).fillna(0)

#     a   b   c   d
#0  1.0 2.0 0.0 0.0
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • Thanks, but is there a way to execute it `inplace=True?` – user3595632 Mar 12 '17 at 21:36
  • 1
    It doesn't seem so. Maybe `df = df.append(counter, ignore_index=True).fillna(0)`. Not `inplace` though. – Psidom Mar 12 '17 at 21:40
  • 2
    `inplace=True` doesn't really [do much anyway](http://stackoverflow.com/a/22533110/487339). – DSM Mar 12 '17 at 21:48
  • While it might not have been possible for OP, [more efficient to make dataframe with all data at the end](https://stackoverflow.com/questions/27929472/improve-row-append-performance-on-pandas-dataframes). This [question and answer dealing with counters](https://stackoverflow.com/a/41192439/8508004) might help. For adapting that example to something similar to what guess OP was attempting here, I'd accumulate a dictionary of counter objects and then create the dataframe with `df = pd.DataFrame.from_dict(d, orient='index').fillna(0)`. – Wayne Jan 04 '19 at 15:31