首页 > 解决方案 > 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.

标签: pythonpandas

解决方案


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+


推荐阅读