简体   繁体   中英

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+

I guess the function should be (couldn't edit it):

def test(df1,keys=["price"]):
    x=df1.groupby(keys).size()
    x.to_csv("%" % (df1),sep='\t')

A way to do it is:

def test_updated(df,filename,keys=["price"]):
    x=df.groupby(keys).size()
    filename = "{}s_price.txt".format(filename)
    x.to_csv(filename,sep='\t')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM