如果我有了這樣的混合值我如何做一個熊貓系列的元素條件分支?
一個S系列textelement
{"id":1,"name":"whatever","value":"sonso"}
name-value
我怎麼做一個條件語句,這樣,當元素是JSON格式,它會跳過,但是當它是一個文本字符串或名稱 - 值對,我會轉換爲JSON格式?
如果我有了這樣的混合值我如何做一個熊貓系列的元素條件分支?
一個S系列textelement
{"id":1,"name":"whatever","value":"sonso"}
name-value
我怎麼做一個條件語句,這樣,當元素是JSON格式,它會跳過,但是當它是一個文本字符串或名稱 - 值對,我會轉換爲JSON格式?
可以通過str.startswith
濾除由boolean indexing
和mask
json
格式:
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
Whas期望從濾波後的輸出JSON從樣本數據? – jezrael