简体   繁体   English

如何将文件名插入“to_csv”

[英]how to insert file name into "to_csv"

I have the following python formula to summarize price in a dataframe.我有以下 python 公式来汇总数据框中的价格。

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.我想将文件名 (df_Example) 放入输出文件中,所以我使用了 %s 但这不起作用。 Does anyone know how to fix this?有谁知道如何解决这一问题?

Thank you.谢谢你。

You could use f-strings:您可以使用 f 字符串:

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 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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