Pandas update multiple columns at once

后端 未结 2 648
青春惊慌失措
青春惊慌失措 2021-02-05 04:55

I\'m trying to update a couple fields at once - I have two data sources and I\'m trying to reconcile them. I know I could do some ugly merging and then delete columns, but was

2条回答
  •  清歌不尽
    2021-02-05 05:14

    you want to replace

    print df.loc[df['Col1'].isnull(),['Col1','Col2', 'Col3']]
    
      Col1 Col2 Col3
    2  NaN  NaN  NaN
    3  NaN  NaN  NaN
    

    With:

    replace_with_this = df.loc[df['Col1'].isnull(),['col1_v2','col2_v2', 'col3_v2']]
    print replace_with_this
    
      col1_v2 col2_v2 col3_v2
    2       a       b       d
    3       d       e       f
    

    Seems reasonable. However, when you do the assignment, you need to account for index alignment, which includes columns.

    So, this should work:

    df.loc[df['Col1'].isnull(),['Col1','Col2', 'Col3']] = replace_with_this.values
    
    print df
    
      Col1 Col2 Col3 col1_v2 col2_v2 col3_v2
    0    A    B    C     NaN     NaN     NaN
    1    D    E    F     NaN     NaN     NaN
    2    a    b    d       a       b       d
    3    d    e    f       d       e       f
    

    I accounted for columns by using .values at the end. This stripped the column information from the replace_with_this dataframe and just used the values in the appropriate positions.

提交回复
热议问题