python - how to insert file name into "to_csv"
问题描述
I have the following python formula to summarize price in a dataframe.
def test(df1,keys=["price"]):
x=df1.groupby(keys).size()
x.to_csv("%s_price.txt" % (df1),sep='\t')
I tried as follows.
test(df_Example,keys=["price"])
I want to put file name (df_Example) into the output file, so I used %s but this did not work. Does anyone know how to fix this?
Thank you.
解决方案
You could use f-strings:
def test(df1, filename, keys=["price"]):
x = df1.groupby(keys).size()
x.to_csv(f"{filename}_price.txt", sep='\t')
test(df_Example, "df_Example.csv", keys=["price"])
I think it only works in python 3.6+
推荐阅读
- python - Python导入问题只能运行应用程序或代码但不能同时运行
- python - 执行Nuitka编译的.exe程序时如何隐藏cmd控制台?
- elasticsearch - 如何根据分数对 ElasticSearch 文档进行排名
- javascript - 如何在 Javascript 中插入外部 Javascript 链接(例如 VS-Code 中的示例),因为它已插入 Codepen?
- python - “运行时错误:未找到应用程序。” 使用 SQLAlchemy 进行单元测试时
- flutter - 飞镖的路径如何修复?
- c++ - 指针删除 C++
- javascript - JS-Dos 6.22:禁用操纵杆
- haskell - 是否可以将值提升到类型级别?
- php - 如何仅在 laravel 中使用 DATE 获取数据?