如何在 Python 中获取 DataFrame 的名称?

How can I get the name of a DataFrame in Python?

我有以下 python 功能可以将数据框导出到 csv 文件。我使用下面的脚本调用它

finalExport(dataAllR, sourcePath, header, started)

def finalExport(data, exportPath, header, te):
    print('# USDF: "finalExport" :-')
    exportPath = exportPath + '\final_py_upload' + data + '.csv'
    data.to_csv(exportPath, columns = header, sep = ',', index = False)
    print('Process done, result file stored in: ', exportPath)
    if te != '': tpe(te)
    return

我想使用数据框的名称,即我在脚本中调用函数时传递的 dataAllR

exportPath = exportPath + '\final_py_upload' + data + '.csv'
#                                                ^

我想根据数据框名称生成文件名。

请帮忙解决这个问题。

由于 Python 允许您将任意属性名称分配给对象,您可以将名为 name 的属性分配给数据框以表示它的名称:

import pandas as pd 
df = pd.DataFrame()
df.name = 'My Data Frame'
print(df.name) # My Data Frame

在您的情况下,在为 dataAllR 定义 name 属性后:

dataAllR.name = 'dataAllR'

您将使用:

exportPath = exportPath + '\final_py_upload' + data.name + '.csv'

或者,甚至更好:

exportPath = f'{exportPath}\final_py_upload{data.name}.csv'

事实是 Python 值没有 名称,它们 绑定到 名称(有时- 见第二个例子)。当我写

a = "a string"
b = a

"a string" 叫什么名字? ab,或两者兼而有之?同样,当我写

lst = ["orange", "banana", "apple"]

"apple" 的名字是什么? lst[2] 不是名称,它是对容器元素的引用。 This video by Ned Batchelder 讨论了那些对 Python 还比较陌生的潜在混淆来源。

不幸的是 (?) Pandas 数据帧没有 name 属性或类似的东西。考虑到 Python 的灵​​活性,很容易定义一个 NamedDataFrame 子类来维护这样一个属性,尽管您首先会面临如何派生这些名称的问题。