I have a list of dataframes, I want to add a new column to each dataframe that is the name of the dataframe.
df_all = [df1,df2,df3]
for df in df_all:
df["Loc"] = df[df].astype.(str)
Boolean array expected for the condition, not object
is this possible to achieve?
CodePudding user response:
You can't do this, python objects have no possibility to know their name(s).
You could emulate it with:
df_all = [df1, df2, df3]
for i, df in enumerate(df_all, start=1):
df['Loc'] = f'df{i}'
Alternatively, use a dictionary:
df_all = {'df1': df1, 'df2': df2, 'df3': df3}
for k, df in df_all.items():
df['Loc'] = k
CodePudding user response:
It can be done with using the system's locals()
dictionary, which contains variable names and references, and the is
operator to match.
df1, df2, df3 = pd.DataFrame([1, 1, 1]), pd.DataFrame([2, 2, 2]), pd.DataFrame([3, 3, 3])
df_all = [df1, df2, df3]
_df = k = v = None
for _df in df_all:
for k, v in locals().items():
if v is _df and k != '_df':
_df["Loc"] = k
print(*df_all, sep='\n\n')
0 Loc
0 1 df1
1 1 df1
2 1 df1
0 Loc
0 2 df2
1 2 df2
2 2 df2
0 Loc
0 3 df3
1 3 df3
2 3 df3