You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Pandas DataFrame的名称添加为DataFrame中的一列?

Fix: Adding DataFrame Name as a Column

Let me help you resolve this issue! The problem with your current code is that you’re trying to assign a non-existent NAME column to itself, which won’t work—what you actually want is to set the new column to the string name of your DataFrame (like "DF_NAME").

Single DataFrame Solution

Here’s the corrected code for a single DataFrame:

import pandas as pd

# Load your CSV file
DF_NAME = pd.read_csv('CSV_LOCATION', encoding="ISO-8859-1")
# Add a new column 'NAME' with the DataFrame's name as the fixed value
DF_NAME['NAME'] = 'DF_NAME'

The key change here is using the string literal 'DF_NAME' instead of DF_NAME.NAME—this directly sets every row in the new NAME column to the name you’ve given your DataFrame.

Batch Solution (Multiple DataFrames)

If you have several DataFrames to process, using a dictionary to store them will make this task much cleaner and avoid repetitive code:

import pandas as pd

# Create a dictionary mapping DataFrame names to their loaded CSV files
dfs = {
    'sales_data': pd.read_csv('sales.csv', encoding="ISO-8859-1"),
    'customer_data': pd.read_csv('customers.csv', encoding="ISO-8859-1"),
    'inventory_data': pd.read_csv('inventory.csv', encoding="ISO-8859-1")
}

# Iterate through the dictionary to add the name column to each DataFrame
for df_name, df in dfs.items():
    df['NAME'] = df_name

# Access individual DataFrames later like this:
# dfs['sales_data']

This approach automatically assigns the correct name to each DataFrame’s NAME column without manual repetition.

Why Your Original Code Failed

DF_NAME.NAME tries to access an existing column named NAME in your DataFrame, which doesn’t exist yet. This would throw an AttributeError or KeyError because the column hasn’t been created. By using the string version of your DataFrame’s name, you’re explicitly setting the value you want for the new column.

内容的提问来源于stack exchange,提问作者Analyst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:01:03