我有一个pandas dataframe列,其中包含以下json格式:
{"events": null, "game": "yes", "catch": "yes", "throw": null}
{"events": null, "game": "yes", "catch": "no", "throw": null}
打印(df_merge['PDH_Value'].head().to_dict())
{0:{roth:null,pretax:null,catchup:“false”,“postax:null}”,1:{roth:null,pretax:“true”,“catchup:“true”,“postax:null}”,2:“,3:{roth:null,”pretax:“true”,“catchup:“true”,“postax:null}”,4:{roth:“true”,“pretax:“true”,“catchup:“true”,“catchup:”true”,“postax:“true”}”
我只想迭代并从json中获取catch值,即“yes”、“no”,并将其存储在同一个dataframe列中
所需输出:
df_merge['PDH_Value']
true
false
尝试了代码并出现以下错误:
pd.json_normalize(df_merge['PDH_Value'].apply(json.loads))['catch']
raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
让我们从这里开始:
解释:
然后:
解释:
由于df_merge['PDH_Value']的值仍然是字符串,因此我们正在检查序列中的值,即df_merge['PDH_Value']是否以
{
开头,或者如果它以{
开头,则我们不会对其进行任何更改,但如果它没有开始,则我们将其替换为"{'catchup':'None'}"
…换句话说,我们正在将空字符''
替换为"{'catchup':'None'}"
,因为您只对“catchup”感兴趣在使用astype()之后,我们将确保所有内容都是字符串,然后通过
map()
方法将值传递给literal_eval()
,因此现在df_merge['PDH_Value']
内的字符串将转换为实际的字典因为它现在是实际的字典,所以我们通过
map()
方法获取'catchup'
键的值最后:
解释:
因为我们使用的是
str.title()
,所以True和False是大写的T和F(第一个字母大写,其余字母小写)因为您只需要yes和no,并且如果您确定dict中的所有值都是小写的,那么您可以从上述方法中删除
str.title()
,因此它变为:df_merge['PDH_Value']=df_merge['PDH_Value'].map({'true':'yes','false':'no','None':float('nan')})
map()
映射值,即类似于替换,您也可以使用replace()
代替map()
,因此我们将true
更改为yes
,反之亦然,None
更改为NaN
我的方法类似于@Anurag Dabas,但有
json.loads
:相关问题 更多 >
编程相关推荐