Reputation: 988
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
Expected output as below:
Upvotes: 0
Views: 220
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
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