2016-10-28 29 views
1

如果我有了這樣的混合值我如何做一個熊貓系列的元素條件分支?

一個S系列
textelement 
{"id":1,"name":"whatever","value":"sonso"} 
name-value 

我怎麼做一個條件語句,這樣,當元素是JSON格式,它會跳過,但是當它是一個文本字符串或名稱 - 值對,我會轉換爲JSON格式?

+0

Whas期望從濾波後的輸出JSON從樣本數據? – jezrael

回答

1

可以通過str.startswith濾除由boolean indexingmaskjson格式:

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 
+0

不錯,但是如果我想在輸出文本字符串和名稱 - 值對之後輸出JSON中的所有元素呢? – socnis

+0

然後用's1 = s [mask]' – jezrael

+0

和's2 = s [〜mask]' – jezrael