如何将Pandas DataFrame的名称添加为DataFrame中的一列?
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

