我有一个导入为数据框的json文件。列之一包含字典列表。我需要将每一行的字典分成几列。
import urllib
import json
import requests
from pandas.io.json import json_normalize
f = requests.get(url)
data = json.loads(f.text)
docs = json_normalize(data['documents'])
display(docs)
doc_num sentence categories
1 "I am a dog" [{"id" : "A"}, {"id" : "B"}, {"id" : "C"}]
2 "I am a cat" [{"id" : "C"}, {"id" : "D"}, {"id" : "E"}]
... ... ...
我希望DataFrame看起来像是:
doc_num sentence cat_A cat_B cat_C cat_D ...
1 "I am a dog" 1 1 1 0
2 "I am a cat" 0 0 1 1
... ... ... ... ... ...
我希望DataFrame将字典列表分成单独的列,如果该列属于该类别,则该列为“ 1”,如果不属于该类别,则为“ 0”。
答案 0 :(得分:0)
这可能会有所帮助。我认为代码是可以理解的,但是如果您需要帮助,请告诉我。我测试了输出。
df = pd.DataFrame(data={'categories':[[{'id':'A'},{'id':'B'},{'id':'C'}],[{'id':'B'},{'id':'D'}],[{'id':'C',}]]})
all_keys = {}
def get_all_keys(x):
for d in x:
if d['id'] not in all_keys:
all_keys[d['id']] = 1
_,df['categories'].apply(get_all_keys)
for i,key in enumerate(all_keys.keys()):
all_keys[key] = i
mat = np.zeros((df.shape[0],len(all_keys.keys())),dtype=np.int)
print(mat.shape)
def f(i,x):
for d in x:
key = d['id']
key_index = all_keys[key]
mat[i][key_index]=1
for i,row in df.iterrows():
print(i,row)
f(i,row['categories'])
new_df = pd.DataFrame(data=mat,columns=all_keys.keys())
df = pd.concat([df,new_df],axis=1)