如果我有一个具有混合值的系列S
textelement
{"id":1,"name":"whatever","value":"sonso"}
name-value
如何创建条件语句,以便当元素为JSON格式时,它将跳过,但当它是文本字符串或名称 - 值对时,我将转换为JSON格式?
答案 0 :(得分:1)
您可以按boolean indexing
过滤json
格式,str.startswith
过滤mask
格式:
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