我正在将数据写入文件。该代码的一部分涉及将Series写入文件。我知道如何通过使用to_csv
来简单地将Series写入文件,但是我在这里要做的是写一堆行,然后我要显示Series的内容。我还没弄清楚怎么做。
我只是尝试做类似的事情:
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)
这是我的数据系列:
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()
这是我的数据框:
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
输出仅显示系列名称,而不是实际内容:
This report is for todays data
Please see the breakdown based on items sold
df_fridge_grp
代替:
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
答案 0 :(得分:1)
您可能想对to_string()做些什么
print(df_fridge_grp.to_string())
或针对您的用例:
fileWrite.write(df_fridge_grp.to_string())
答案 1 :(得分:0)
以下代码:
fileWrite.write(df_fridge_grp)
不是您要获得该输出所要执行的操作,否则将得到TypeError: write() argument must be str, not DataFrame
。您可能做到了:
fileWrite.write("df_fridge_grp")
这不会存储数据帧,因为这只是一个字符串。正确的方法是获取数据框的字符串表示形式并将其存储。您可以这样做:
fileWrite.write(str(df_fridge_grp))
fileWrite.close()
始终确保关闭文件!