[英]Evaluate a string to a dictionary when there are null values in the dictionary
我有一個看起來像這樣的數據框(Thing_2被評估為字符串):
ID Thing Thing_2
1 abc [{"object_1": "a", "object_2": null}]
2 def None
我希望它看起來像這樣:
ID Thing Thing_2
1 abc a
2 def None
為此,我執行了以下步驟:
def change_to_dict(row):
t2 = row['Thing_2']
if pd.notna(row['Thing_2']):
t2 = t2.strip('[]')
t2 = ast.literal_eval(t2)
return t2.get[0]
我不斷在不為null的索引處收到value_error:格式錯誤的節點。 我認為這是因為字典中的第二個值是空值。
嘗試:
import json
def change_to_dict(row):
t2 = row['Thing_2']
if pd.notna(t2):
t2_content = json.loads(t2)
return ','.join(filter(bool, t2_content[0].values()))
據我了解,我不知道這是否適合您。
>>> df
ID Thing Thing_2
0 1 abc [{"object_1": "a", "object_2": null}]
1 2 def None
您可以使用re模塊來實現這一點,但必須定義需要從列中提取的字符串/字符。
>>> search_list = ['a']
>>> import re
>>> df['Thing_2'] = df.Thing_2.str.extract('({})'.format('|'.join(search_list)), flags=re.IGNORECASE, expand=False).str.lower().fillna('None')
>>> df
ID Thing Thing_2
0 1 abc a
1 2 def None
如果您要針對特定的列(例如)搜索一些字符串/單詞,這很有a
。
這應該工作。
import yaml
def change_to_dict(row):
if pd.notna(row):
t2 = row
t2 = t2.strip('[]')
t2 = yaml.load(t2)
return list(t2.values())[0]
df['Thing_2'].apply(lambda x: change_to_dict(x))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.