pandas series.str.sum automatically ignore illegal data

Viewed 30

data

data = [
    {"content": "1", "title": "appstore", "info": "", "time": 1578877014},
    {"content": "2", "title": "app", "info": "", "time": 1579877014},
    {"content": "3", "title": "a", "info": "", "time": 1582877014},
    {"content": "12", "title": "jack", "info": "", "time": 1582876014},
    {"content": "aa", "title": "apple", "info": "", "time": 1581877014},
    {"content": "16", "title": "banana", "info": "", "time": 1561877014},
]

my code

s = pd.Series(data)

print('-'*100)
print(s.str.get('content').sum())

I also think this is crazy, but the data does have dirty data. i hope data

1+2+3+12+16=36
## calc sum automatically ignore illegal data
{"content": "aa", "title": "apple", "info": "", "time": 1581877014}
1 Answers

Use to_numeric with errors='coerce' for replace bad values to NaNs and also convert strings numbers to numeric, so output is:

print(pd.to_numeric(s.str.get('content'), errors='coerce').sum())
34.0
Related