If I have a series S that has such mixed values
textelement
{"id":1,"name":"whatever","value":"sonso"}
name-value
how do I make a conditional statement so that when the element is in JSON format, it will skip, but when it's a text string or name-value pair, I will convert to JSON format?
You can filter out json
format by boolean indexing
and mask
by str.startswith
:
s = pd.Series(['textelement',{"id":1,"name":"whatever","value":"sonso"}, 'name-value'])
print(s)
0 textelement
1 {'id': 1, 'value': 'sonso', 'name': 'whatever'}
2 name-value
dtype: object
#cast all values to string
s = s.astype(str)
#check which string starts with `{`
mask = s.str.startswith('{')
print (mask)
0 False
1 True
2 False
dtype: bool
print (~mask)
0 True
1 False
2 True
dtype: bool
#filter by inverted mask with ~
s = s[~mask]
print (s)
0 textelement
2 name-value
dtype: object
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments