Home > Blockchain >  Concatenate a a string and integer to make a new column for each dataframe in a list of dataframes
Concatenate a a string and integer to make a new column for each dataframe in a list of dataframes

Time:09-19

I want to make a new column for each dataframe in a list of dataframes called "RING" which contains the word "RING" the another column called "No".

here is my solution so far

df_all = [df1,df2,df3]

for df in df_all:
    df["RING "] = "RING"   str(df['No'])
    
df_all

Is there away that doesn't require a for loop?

CodePudding user response:

You are almost there:

df_all = [df1,df2,df3]

for df in df_all:
    df["RING"] = "RING"   df["No"]
    
    # If df["No"] is not of type string, cast it to string:
    # df["RING"] = "RING"   df["No"].astype("str")
    
df_all

CodePudding user response:

  • you can concat all dataframes in the list to get one df (then work with it):
df_all = [df1,df2,df3]
df = pd.concat(df_all, axis=0, ignore_index=True)
df["RING "] = "RING"   df['No'].astype(str)
  • if you want to come bak and get separate dataframes, you can do this:
df_all = [df1,df2,df3]
df1['df_id'] = 1
df2['df_id'] = 2
df3['df_id'] = 3

df = pd.concat(df_all, axis=0, ignore_index=True)
df["RING "] = "RING"   df['No'].astype(str)

#--> 
df1 = df.loc[df['df_id'].eq(1)]
df2 = df.loc[df['df_id'].eq(2)]
df3 = df.loc[df['df_id'].eq(3)]
  • if you don't want use concat, you can try list comprehension, usually faster than for loop:
df_all = [df1,df2,df3]

def process_df(df):
    df["RING "] = "RING"   df['No'].astype(str)
    return df

processed_df_all = [process_df(df) for df in df_all]
#df1 = processed_df_all[0]
  • Related