简体   繁体   中英

Replace values in pandas data frame conditionally

I have two datasets loaded into Pandas DataFrames from Excel files. I'm trying to replace the Cases value in d1 from d2 where the County name matches.

Here are two example datasets:

d1 = { 
  'County': ['Armstrong', 'Bailey', 'Bexar', 'Borden', 'Briscoe', 'Carson', 'Castro'],
  'Cases': [80, 548, '', 'online', 58, 'online', 0]
}
d2 = {
  'County': ['Bexar', 'Borden', 'Carson', 'Castro'],
  'Cases': [16891, 1296, 1674, 1985]
}

I'm new to Pandas and could really just use some guidance if not a complete answer.

I'd expect print(d1.to_string()) output to look like this after the merge/replacement has been completed:

Name       Count
Armstrong  80
Bailey     548
Bexar      16891
Borden     1296
Briscoe    58
Carson     1674
Castro     1985

Why not use pandas.DataFrame.update

>>> df1 = pd.DataFrame(d1).set_index('County')
>>> df2 = pd.DataFrame(d2).set_index('County')
>>> df1.update(df2)  # works "inplace"
>>> df1
           Cases
County          
Armstrong     80
Bailey       548
Bexar      16891
Borden      1296
Briscoe       58
Carson      1674
Castro      1985

?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM