Search code examples
dataframecalculated-columns

Can I add a new colum to a data frame with only one value assigned to a specifc row and the other rows be a different value?


I would like to add a column to my data frame and assign the first row value for that column a specific number...every other row would be na or 0 for the time being until changed later on.


Solution

  • Code-

    import pandas as pd
    
    data={'email':['xyz@xyz.com','xyz1@xyz.com','xyz2@xyz.com','xyz3@xyz.com'],'Difference':[15,23,45,23],'Mean':[14,26,42,29]}
    
    df=pd.DataFrame(data)
    
    # df['buy'] = df.iloc[0, df.columns.get_loc('buy')] = "x"
    #Create new col with NAN values
    df["new_col"] = np.nan #or " " 
    df.iloc[0, df.columns.get_loc('new_col')] = 1 #assign value to 1st row
    df #print the dataframe
    

    Output-

    
                email       Mean    new_col
    0       xyz@xyz.com     15      1.0
    1       xyz1@xyz.com    23      NaN
    2       xyz2@xyz.com    45      NaN
    3       xyz3@xyz.com    23      NaN
    

    Ref link-https://stackoverflow.com/questions/31569384/set-value-for-particular-cell-in-pandas-dataframe-with-iloc