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?

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but is there a way to execute it inplace=True?
It doesn't seem so. Maybe df = df.append(counter, ignore_index=True).fillna(0). Not inplace though.
inplace=True doesn't really do much anyway.
While it might not have been possible for OP, more efficient to make dataframe with all data at the end. This question and answer dealing with counters 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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.