2016-10-28 6 views
1

나는 그런 혼합 값팬더 시리즈의 요소에 조건부 분기를 수행하려면 어떻게해야합니까?

이있는 시리즈 S가있는 경우 요소는 JSON 형식 일 경우에, 그것은 건너 뛸 수 있도록 내가 조건문을하지만 텍스트 문자열 또는 때 어떻게
textelement 
{"id":1,"name":"whatever","value":"sonso"} 
name-value 

이름 - 값 쌍, JSON 형식으로 변환하겠습니까?

+0

Whas 샘플 데이터로부터 필터링 된 출력에서 ​​원하는 JSON입니까? – jezrael

답변

1

str.startswith 의해 boolean indexingmask 의해 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 
+0

멋진데, 텍스트 문자열과 이름 - 값 쌍을 변환 한 후 JSON의 모든 요소를 ​​출력하려면 어떻게해야합니까? – socnis

+0

그런 다음's1 = s [mask]'를 사용하십시오. – jezrael

+0

그리고's2 = s [~ mask]' – jezrael

관련 문제