展平嵌套 JSON 并使用 pandas 连接到数据框
Flatten nested JSON and concatenate to dataframe using pandas
网上找了很多类似的题目,还没找到解决方法
我的 pandas 数据框如下所示:
index FOR
0 [{'id': '2766', 'name': '0803 Computer Softwar...
1 [{'id': '2766', 'name': '0803 Computer Softwar...
2 [{'id': '2766', 'name': '0803 Computer Softwar...
3 [{'id': '2766', 'name': '0803 Computer Softwar...
4 [{'id': '2766', 'name': '0803 Computer Softwar...
我想将所有 4 行展平成如下数据框,而下面只是第一行的结果:
index id name
0 2766 0803 Computer Software
我找到了类似的解决方案 here。不幸的是,我收到如下“TypeError”:
类型错误:JSON 对象必须是 str、bytes 或 bytearray,而不是 'list'
我的代码是:
dfs = []
for i in test['FOR']:
data = json.loads(i)
dfx = pd.json_normalize(data)
dfs.append(dfx)
df = pd.concat(dfs).reset_index(inplace = True)
print(df)
有人可以帮我吗?
非常感谢!
尝试使用 ast
标准库中的 literal_eval
。
from ast import literal_eval
df_flattened = pd.json_normalize(df['FOR'].map(literal_eval))
然后删除重复项。
print(df_flattened.drop_duplicates())
id name
0 2766 0803 Computer Software
几周没有接触相关作品后,
我遇到了另一个类似的情况,并且
我想到目前为止我已经找到了这个案例的解决方案。
请随时纠正我或提供任何其他想法。
我非常感谢所有的帮助和慷慨的支持!
chuck = []
for i in range(len(test)):
chuck.append(json_normalize(test.iloc[i,:]['FOR']))
test_df = pd.concat(chuck)
然后删除 test_df
的重复列
网上找了很多类似的题目,还没找到解决方法
我的 pandas 数据框如下所示:
index FOR
0 [{'id': '2766', 'name': '0803 Computer Softwar...
1 [{'id': '2766', 'name': '0803 Computer Softwar...
2 [{'id': '2766', 'name': '0803 Computer Softwar...
3 [{'id': '2766', 'name': '0803 Computer Softwar...
4 [{'id': '2766', 'name': '0803 Computer Softwar...
我想将所有 4 行展平成如下数据框,而下面只是第一行的结果:
index id name
0 2766 0803 Computer Software
我找到了类似的解决方案 here。不幸的是,我收到如下“TypeError”: 类型错误:JSON 对象必须是 str、bytes 或 bytearray,而不是 'list'
我的代码是:
dfs = []
for i in test['FOR']:
data = json.loads(i)
dfx = pd.json_normalize(data)
dfs.append(dfx)
df = pd.concat(dfs).reset_index(inplace = True)
print(df)
有人可以帮我吗? 非常感谢!
尝试使用 ast
标准库中的 literal_eval
。
from ast import literal_eval
df_flattened = pd.json_normalize(df['FOR'].map(literal_eval))
然后删除重复项。
print(df_flattened.drop_duplicates())
id name
0 2766 0803 Computer Software
几周没有接触相关作品后, 我遇到了另一个类似的情况,并且 我想到目前为止我已经找到了这个案例的解决方案。 请随时纠正我或提供任何其他想法。 我非常感谢所有的帮助和慷慨的支持!
chuck = []
for i in range(len(test)):
chuck.append(json_normalize(test.iloc[i,:]['FOR']))
test_df = pd.concat(chuck)
然后删除 test_df
的重复列