Lilly
Lilly

Reputation: 988

Write word count frequency from python list into a csv file

I have a list as below (test_list) I am trying to do word count frequency, sort by counts and want to write as a csv along with header. I have tried as below.

test_list = ['ball', 'cat', 'mat', 'ball', 'cat', 'ball', 'ball', 'ink']
items = pd.Series(test_list).value_counts().sort_values(ascending=False)
items.columns = ['items', '#counts']
df.to_csv(r'C:\Users\word_count.csv',header=True)

But my output csv is without header and there is 0 on top as below

enter image description here

Expected output as below:

enter image description here

Upvotes: 0

Views: 220

Answers (2)

Anurag Dabas
Anurag Dabas

Reputation: 24322

just chain reset_index() method in your current code:

items = pd.Series(test_list).value_counts().sort_values(ascending=False).reset_index()

Now Finally:

items.columns = ['items', '#counts']
df.to_csv(r'C:\Users\word_count.csv',header=True,index=False)

Upvotes: 3

Nk03
Nk03

Reputation: 14949

convert series to dataframe and then rename the columns. Finally, save the df.

df = items.to_frame(name = 'count')
df.index.name = 'item'
df.to_csv('test.csv', index=False)

Upvotes: 2

Related Questions