2

I have a dictionary in python called word_counts consisting of key words and values which represent the frequency in which they appear in a given text:

word_counts = {'the':2, 'cat':2, 'sat':1, 'with':1, 'other':1}

I now need to make this into a pandas DataFrame with two columns: a column named 'word' indicating the words and column named 'count' indicating the frequency.

pdfranco
  • 31
  • 1

3 Answers3

0
>>> import pandas as pd
>>> pd.DataFrame(list(word_counts.items()), columns=['word', 'count'])
    word  count
0    the      2
1    cat      2
2    sat      1
3   with      1
4  other      1
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – β.εηοιτ.βε May 21 '20 at 18:54
0

you can create a dataframe from a dictonary:

df=pd.DataFrame({"word":list(word_counts.keys()) , "count": list(word_counts.values())})
Xalemon
  • 36
  • 4
0

you can use the .from_dict appendage from pd.DataFrame

pd.DataFrame.from_dict(word_counts, orient="index", columns=["Count"]).rename_axis(
    "Word", axis=1
)
Word   Count
the        2
cat        2
sat        1
with       1
other      1
Umar.H
  • 22,559
  • 7
  • 39
  • 74