在由循环创建的数据框中,向随迭代增加的列添加后缀

In dataframes created by a loop, add suffix to columns that increases with iteration

我正在通过循环创建编号从 1 到 n 的多个数据帧。 我为此做的第一件事是创建一个字典:

dict_of_df = {}

然后运行循环:

for i in range(1, n+1): 
    ... import data
    ... manipulate data
    ... create a dataframe corresponding to the "i" value of the loop
    dict_of_df["df_{}".format(i)] = _my_last_manipulated_data_

这会创建一个名为 df_1df_2...df_n 的数据帧字典,我可以在循环外访问它们中的每一个以进一步处理:

df_1 = dict_of_df["df_1"]
df_2 = dict_of_df["df_2"]
...
etc

问题是我导入的数据非常相似,循环产生的所有数据帧,df_1df_2,... df_n,都相同共享相同名称的列数;也就是说,所有 df_i 都有 4 列名称 ABCD.

为了在创建 df_1 时获得名称 A_1B_1C_1D_1,我可以在循环中做什么,然后A_2B_2C_2D_2df_2 被创建时,等等......?

我想循环的最后一行 dict_of_df["df_{}".format(i)] = ... 应该修改,但我看不出要修改什么。我想在某处引入enumerate,但我不知道具体是什么形式。

IIUC,你可以使用add_suffix方法。因此,在循环的最后一行使用下面的行:

dict_of_df["df_{}".format(i)] = _my_last_manipulated_data_.add_suffix(f'_{i}')