【问题标题】:Elegant way to fetch the dataframe name and save the file with same name获取数据框名称并以相同名称保存文件的优雅方式
【发布时间】:2019-08-22 07:30:11
【问题描述】:

我有两个数据框 test1test2。我的程序逻辑如下

def write_file():
   test1.to_csv(('test1.csv'),index=None)

def process_file():
    test2= pd.read_csv('test1.csv',low_memory=False)

def write_processed_file():
   test2.to_csv(('test2.csv'),index=None)

我像下面这样调用上述所有函数

write_file()
process_file()
write_processed_file()

如您所见,我有两个 write 函数仅用于编写数据帧,因为我希望两个数据帧的 .csv 文件名不同。如果我按照下面的input argument 方法只有一个写入函数,那么我只能有一个通用文件名。我们如何获得 datframe 名称?

def write_file(df_name):
   df_name.to_csv(('common_file_name.csv'),index=None)

我希望我的输出有两个名为 test1.csvtest2.csv 的 csv 文件,而没有两个写入函数

基本上我有 400-500 行代码,如果代码将数据帧写入 csv 文件,则有 15-18 行。我想要一个写入函数,它接受数据框作为输入,并提供数据框的名称作为 csv 文件名。

有没有办法以优雅高效的方式获取数据框名称并保存同名文件?

【问题讨论】:

    标签: python python-3.x pandas dataframe file-writing


    【解决方案1】:

    在代码中使用变量名被认为是不好的风格。虽然在 Python 中是可能的,但我建议只传递两个参数:

    def write_file(df, filename):
        df.to_csv(filename, index=None)
    

    你可以在你的代码中使用它

    write_file(test1, 'test1.csv')
    write_file(test2, 'test2.csv')
    

    现在,如果您有许多数据帧都遵循上述可预测的命名模式怎么办?在这种情况下,最好使用列表来保存数据框。

    test = [test1, test2, test3, ..., test100]
    

    然后你可以索引到这个列表中,循环写入文件

    for i, df in enumerate(test, 1):
        write_file(df, f'test{i}.csv')
    

    但是,如果您有许多数据框并且名称不是可预测的数字模式怎么办?那我宁愿用字典:

    dfs = {'test1': test1, 
           'test2': test2,
           'other_df': other_df,
           'inline_df': process_df()  # you can store them straight from a function
           }
    
    for name, df in dfs.items():
        write_file(df, f'{name}.csv')
    

    【讨论】:

    • 但是您知道如何获取数据框名称吗?只是没有字典。我的意思是df.name。我知道这可能意味着名为name 的列,但我怎样才能获得 df 的名称。有没有pythonic方法可以做到这一点?
    • 就像我提到的那样,在代码中使用变量的名称并不是一种好的做法。理解起来可能很奇怪,但数据框实际上并没有“具有”名称作为属性,而是名称与内存中的数据框相关联。所以虽然ways may exist,你不应该尝试这样做。请参阅how names work in Python 上的这篇文章。
    • 知道了。谢谢
    • 你能帮我解决这个问题吗? stackoverflow.com/questions/57667919/…
    猜你喜欢
    • 2017-04-20
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2021-08-15
    相关资源
    最近更新 更多