Python Forum
DF value by Column... not sure what to call it
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
DF value by Column... not sure what to call it
#2
(Aug-26-2023, 04:54 AM)tester_V Wrote: I’d like to create the file for each Employee with the cars sold.
Seems strange to create a file for each,when can have one file(csv,Excel,html...) that has all the info.
If doing some test.
import pandas as pd
from io import StringIO

data = """Cars Sold, Employee Name,
Cadillac CTS, Bill Clinton,
Cadillac XT6, Bill Clinton,
Cadillac Escalade, Bill Clinton,
Mercedes-Benz E-Class, Hillary Clinton,
Mercedes-Benz E-Class E450, Hillary Clinton,
Ford Expedition, Monica Lewinsky,
Ford F-150, Monica Lewinsky,
Ford Pinto, Monica Lewinsky,
Ford Mustang Mach e, Monica Lewinsky"""

data_io = StringIO(data)
df = pd.read_csv(data_io,  skipinitialspace=True)
# Group the data and count
df_count = df.groupby('Employee Name')['Cars Sold'].count()
employee_car_count = df_count.reset_index(name='Car Count')
print(employee_car_count)
Output:
Employee Name Car Count 0 Bill Clinton 3 1 Hillary Clinton 2 2 Monica Lewinsky 4
So now have the info in one place,and can eg use df.to_csv, df.to_excel...
If need to spit up in separate files i would start and prepare data like this.
>>> data = employee_car_count.to_csv(index=False, header=None, line_terminator='\n')
>>> data
'Bill Clinton,3\nHillary Clinton,2\nMonica Lewinsky,4\n'
>>> data_lst = data.splitlines()
>>> data_lst
['Bill Clinton,3', 'Hillary Clinton,2', 'Monica Lewinsky,4']
So now have a list that can loop over and write content to sperate files.
tester_V likes this post
Reply


Messages In This Thread
RE: DF value by Column... not sure what to call it - by snippsat - Aug-26-2023, 10:24 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020