[英]Join json files in Pandas from multiple rows
我得到了一個具有以下格式的數據框(表 1)。 它只有 col1 和 col2,以及 json_col。
id col1 col2 json_col
1 a b json1
2 a c json2
3 b d json3
4 c a json4
5 d e json5
我有一個新表(表 2),我想在我的新表中加入 json 文件
col1 col2 col3 col4 union_json
a b json1
a b d json1 and json3 union
a b d e json1, json3, and json5 union
c a json4
以下是表 1 的示例
df = pd.DataFrame({'col1': ['a', 'a', 'b', 'c', 'd'],
'col2': ['b', 'c', 'd', 'a', 'e'],
'col3': [{"origin":"a","destination":"b", "arc":[{"Type":"763","Number":"20"}]},
{"origin":"a","destination":"c", "arc":[{"Type":"763","Number":"50"}]},
{"origin":"a","destination":"d", "arc":[{"Type":"723","Number":"40"}]},
{"origin":"c","destination":"a", "arc":[{"Type":"700","Number":"30"}]},
{"origin":"d","destination":"e", "arc":[{"Type":"700","Number":"40"}]}]})
並且,這是表 2 的示例:
df = pd.DataFrame({'col1': ['a', 'a', 'a', 'c'],
'col2': ['b', 'b', 'b', 'a'],
'col3': ['', 'd', 'd', ''],
'col4': ['', '', 'e', '']})
json1 和 json2 的聯合應該是這樣的:
[[{"origin":"a","destination":"b", "arc":[{"Type":"763","Number":"20"}]}],
[{"origin":"a","destination":"d", "arc":[{"Type":"723","Number":"40"}]}]]
我希望我正確理解了您的問題:
from itertools import combinations
def fn(x):
out, non_empty_vals = [], x[x != ""]
for c in combinations(non_empty_vals, 2):
out.extend(df1.loc[df1[["col1", "col2"]].eq(c).all(axis=1), "col3"])
return out
df2["union_json"] = df2.apply(fn, axis=1)
print(df2.to_markdown(index=False))
印刷:
col1 | col2 | col3 | col4 | union_json |
---|---|---|---|---|
一個 | b | [{'origin': 'a', 'destination': 'b', 'arc': [{'Type': '763', 'Number': '20'}]}] | ||
一個 | b | d | [{'origin': 'a', 'destination': 'b', 'arc': [{'Type': '763', 'Number': '20'}]}, {'origin': 'a ', '目的地': 'd', 'arc': [{'Type': '723', 'Number': '40'}]}] | |
一個 | b | d | e | [{'origin': 'a', 'destination': 'b', 'arc': [{'Type': '763', 'Number': '20'}]}, {'origin': 'a ', 'destination': 'd', 'arc': [{'Type': '723', 'Number': '40'}]}, {'origin': 'd', 'destination': 'e ', 'arc': [{'Type': '700', 'Number': '40'}]}] |
c | 一個 | [{'origin': 'c', 'destination': 'a', 'arc': [{'Type': '700', 'Number': '30'}]}] |
df1
col1 col2 col3
0 a b {'origin': 'a', 'destination': 'b', 'arc': [{'Type': '763', 'Number': '20'}]}
1 a c {'origin': 'a', 'destination': 'c', 'arc': [{'Type': '763', 'Number': '50'}]}
2 b d {'origin': 'a', 'destination': 'd', 'arc': [{'Type': '723', 'Number': '40'}]}
3 c a {'origin': 'c', 'destination': 'a', 'arc': [{'Type': '700', 'Number': '30'}]}
4 d e {'origin': 'd', 'destination': 'e', 'arc': [{'Type': '700', 'Number': '40'}]}
df2
col1 col2 col3 col4
0 a b
1 a b d
2 a b d e
3 c a
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.