首页 > 解决方案 > 将同一行从 pandas 数据帧多次添加到新行,每次都会更改特定列中的值

问题描述

我有一个这样的df:

    MEMBER_ID FirstName LastName  I    MONTH
0   1          John      Doe      10   0
1   2          Mary      Jones    15   0
2   3          Andy      Right    8    0

我需要创建一个新的 df (df_new),其中包含对应于唯一 MEMBER_ID 的每一行,按“I”列中的次数复制,并且“MONTH”列必须从 0 到最多填充并在原始df中包含'I'的值。例如:第一行 (MEMBER_ID==1) 必须被复制 10 次(“I”的值),唯一的区别是“MONTH”列将从 0 变为 10。之后行继续'MEMBER_ID' 列中的下一个唯一值。所以我需要 df_new 看起来像这样:

    MEMBER_ID FirstName LastName  I    MONTH
0   1          John      Doe      10   0
1   1          John      Doe      10   1
2   1          John      Doe      10   2
3   1          John      Doe      10   3
...
10  1          John      Doe      10   10
11  2          Mary      Jones    15   0
12  2          Mary      Jones    15   1
13  2          Mary      Jones    15   2
...
N-1 3          Andy      Right    8    7
N   3          Andy      Right    8    8 

我试过这个,但它给了我胡言乱语:

df_new=pd.DataFrame(columns=['MEMBER_ID','FirstName','LastName','I','MONTH'])

for i in range(len(df)):
   max_i=df.iloc[i]["I"]  #this gets the value in the "I" column
   for j in range(0,max_i+1): #to append same row max_i+1 times since I need MONTH to start with 0
      df_new.loc[i]=df.iloc[i]  #this picks the whole row from the original df
      df_new["MONTH"]=j      #this assigns the value of each iteration to the MONTH column
      df_new=df_new.append(df_new.loc[i],ignore_index=True)

感谢您的帮助,亲爱的社区!

标签: pythonpandasdataframe

解决方案


我能够通过以下方式修复 SettingWithCopyWarning:

index =0
for i in range(len(df)):
    for j in range(df.iloc[i]["I"]+1):
        row=df.iloc[i]
        df_new=df_new.append(row,ignore_index=True)
        df_new.at[index,'MONTH']=j
        index+=1

df.head()

推荐阅读