Home > OS >  How to export collections counter to CSV file with good format
How to export collections counter to CSV file with good format

Time:10-12

Here is my code:

from collections import Counter

print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
def amount():
    while True:
        try:
            line = input()
        except EOFError:
            break
        contents.append(line)

    return
amount()


count = Counter(contents)
print(count)

When you enter a number or numbers into this, let's say 3, 4 and 5, it will come printed out in this format:

Counter({'3': 1, '4': 1, '5': 1})

I was wondering if it were possible to export this into a CSV file but have it formatted as anything like this:

Column 1  Column 2
3:            1
4:            1
5:            1

CodePudding user response:

You can with Pandas. I'm Just mentioning Myu way to do it...

from collections import Counter

print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
def amount():
    while True:
        try:
            line = input()
        except EOFError:
            break
        contents.append(line)

    return
amount()


count = Counter(contents)
print(count)

import pandas as pd
d = count
df = pd.DataFrame.from_dict(d, orient='index').reset_index()
df.columns =['column1', 'colum2']

df = df.sort_values(by=['column1'],ascending=False)

print(df)
df.to_csv("camo1.csv", encoding='utf-8', index=False)

#output Csv

enter image description here

  • Related