我如何对熊猫系列的元素进行条件分支?

时间:2016-10-28 05:16:01

标签: python json string pandas if-statement

如果我有一个具有混合值的系列S

textelement
{"id":1,"name":"whatever","value":"sonso"}
name-value

如何创建条件语句,以便当元素为JSON格式时,它将跳过,但当它是文本字符串或名称 - 值对时,我将转换为JSON格式?

1 个答案:

答案 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