![](/img/trans.png)
[英]Python - loop through same query with different variables, merge data frames
[英]For loop to merge Data frames
我试图通过循环合并数据帧,因为每个循环都基于不同的列合并数据帧。
以下是我到目前为止所拥有的:
f1 = pd.DataFrame({"color": ["blue", "yellow", "red"],
"abbv": ["b", "y", "r"]})
df2 = pd.DataFrame({"color_1": ["blue", "red", "yellow"],
"color_2": ["yellow", "blue", "red"],
"total": ["green", "purple", "orange"]})
drop_column = df1.columns.tolist()
drop_column.remove("abbv")
co = "color"
dd4 = []
for i in [1,2]:
dd3 = pd.merge(df2,df1,
left_on = f"{co}_{i}",
right_on = "color",
how="left")
dd3 = dd3.rename(columns={"abbv":f"abbv_{i}"}).drop(drop_column, axis=1)
dd4.append(dd3)
print(dd4)
这是输出:
[ color_1 color_2 total abbv_1
0 blue yellow green b
1 red blue purple r
2 yellow red orange y, color_1 color_2 total abbv_2
0 blue yellow green y
1 red blue purple b
2 yellow red orange r]
我正在努力实现的目标:
颜色_1 | 颜色_2 | 全部的 | abbv_1 | abbv_2 |
---|---|---|---|---|
蓝色的 | 黄色的 | 绿色 | 乙 | 是 |
. | . | . | . | . |
. | . | . | . | . |
如果我理解你的问题,你想使用.map
:
m = df1.set_index("color")["abbv"]
df2["abbv_1"] = df2["color_1"].map(m)
df2["abbv_2"] = df2["color_2"].map(m)
print(df2)
印刷:
color_1 color_2 total abbv_1 abbv_2
0 blue yellow green b y
1 red blue purple r b
2 yellow red orange y r
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.