How to update values in a specific row in a Python Pandas DataFrame?

后端 未结 4 1337
猫巷女王i
猫巷女王i 2020-12-02 12:09

With the nice indexing methods in Pandas I have no problems extracting data in various ways. On the other hand I am still confused about how to change data in an existing Da

4条回答
  •  醉酒成梦
    2020-12-02 12:57

    There are probably a few ways to do this, but one approach would be to merge the two dataframes together on the filename/m column, then populate the column 'n' from the right dataframe if a match was found. The n_x, n_y in the code refer to the left/right dataframes in the merge.

    In[100] : df = pd.merge(df1, df2, how='left', on=['filename','m'])
    
    In[101] : df
    Out[101]: 
        filename   m   n_x  n_y
    0  test0.dat  12  None  NaN
    1  test2.dat  13  None   16
    
    In[102] : df['n'] = df['n_y'].fillna(df['n_x'])
    
    In[103] : df = df.drop(['n_x','n_y'], axis=1)
    
    In[104] : df
    Out[104]: 
        filename   m     n
    0  test0.dat  12  None
    1  test2.dat  13    16
    

提交回复
热议问题