Reputation: 341
I am writing data into a file. A part of the code involves writing a Series into the file. I know how to simply write the Series to a file by using to_csv
, but what I am doing here is writing a bunch of lines and then I want to display the content of the Series. I haven't figured out how to do it.
I tried simply doing something like:
fileWrite= open("details.txt", "w")
fileWrite.write("This report is for todays data \n\n")
fileWrite.write("Please see the breakdown based on items sold \n\n")
fileWrite.write(df_fridge_grp)
This is my data series:
fields = ['Date', 'Name', 'SoldItem']
df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
df_fridge = df.loc[(df['SoldItem'] == 'Fridge')]
df_fridge_grp = df_fridge.groupby(["Date", "Name"]).size()
This is my DataFrame:
Dataframe is
Date Name SoldItem
15-Jul Joe TV
15-Jul Joe Fridge
15-Jul Joe Washing Machine
15-Jul Joe TV
15-Jul Joe Fridge
15-Jul Mary Chair
15-Jul Mary Fridge
16-Jul Joe Fridge
16-Jul Joe Fridge
16-Jul Tim Washing Machine
17-Jul Joe Washing Machine
17-Jul Jimmy Washing Machine
17-Jul Joe Washing Machine
17-Jul Joe Washing Machine
The output just prints the series name rather than the actual contents:
This report is for todays data
Please see the breakdown based on items sold
df_fridge_grp
Instead of:
This report is for todays data
Please see the breakdown based on items sold
Date Name Count
15-Jul Joe 2
Mary 1
16-Jul Joe 2
Upvotes: 0
Views: 837
Reputation: 6505
The following code:
fileWrite.write(df_fridge_grp)
is not what you ran to get that output or you would have gotten TypeError: write() argument must be str, not DataFrame
. You probably did:
fileWrite.write("df_fridge_grp")
This is not going to store the dataframe as that is just a string. The correct way to do it is by getting a string representation of the dataframe and storing that. You can do that like this:
fileWrite.write(str(df_fridge_grp))
fileWrite.close()
And always make sure to close your file!
Upvotes: 0
Reputation: 370
You may want to do something with to_string()
print(df_fridge_grp.to_string())
or for your use-case:
fileWrite.write(df_fridge_grp.to_string())
Upvotes: 1