如何将Pandas Series内容与自定义文本一同写入文件
解决Pandas Series写入文件仅显示名称的问题
我懂你的烦恼——直接把Series对象传给file.write()确实只会输出它的名称,这是因为Pandas默认的字符串表示只返回Series的名称和数据类型,不是实际的统计内容。别着急,有两个简单的方法能完美解决你的需求:
方法1:用to_string()转成可读文本格式
这个方法会把Series的索引、统计值都转换成和你在终端/Notebook里看到的一样的完整文本格式。修改你的代码如下:
import pandas as pd # 你的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() # 写入文件的核心修改 with open("details.txt", "w") as fileWrite: fileWrite.write("This report is for todays data \n\n") fileWrite.write("Please see the breakdown based on items sold \n\n") # 关键:用to_string()获取Series的完整内容 fileWrite.write(df_fridge_grp.to_string())
方法2:用to_csv()写入规整的CSV格式
如果你希望Series内容是更结构化的CSV格式(方便后续处理),可以直接把打开的文件对象传给to_csv():
import pandas as pd # 同样的Series生成逻辑... with open("details.txt", "w") as fileWrite: fileWrite.write("This report is for todays data \n\n") fileWrite.write("Please see the breakdown based on items sold \n\n") # 写入CSV格式,设置header=False可以去掉默认的"size"列名 df_fridge_grp.to_csv(fileWrite, header=False)
最终期望输出示例
方法1生成的details.txt内容:
This report is for todays data Please see the breakdown based on items sold Date Name 15-Jul Joe 2 Mary 1 16-Jul Joe 2
方法2生成的CSV格式内容:
This report is for todays data Please see the breakdown based on items sold 15-Jul,Joe,2 15-Jul,Mary,1 16-Jul,Joe,2
另外提醒下:用with open()的上下文管理器会自动帮你关闭文件,比手动调用file.close()更安全可靠哦~
内容的提问来源于stack exchange,提问作者user3423407
相关产品推荐
相关产品推荐

