gpt4 book ai didi

python - Pandas 合并或加入较小的数据框

转载 作者:行者123 更新时间:2023-12-01 01:42:44 24 4
gpt4 key购买 nike

我有一个问题,我有一个长数据帧和一个短数据帧,我想合并,以便较短的数据帧重复自身以填充较长(左)df 的长度。

df1:

| Index | Wafer | Chip | Value |
---------------------------------
| 0 | 1 | 32 | 0.99 |
| 1 | 1 | 33 | 0.89 |
| 2 | 1 | 39 | 0.96 |
| 3 | 2 | 32 | 0.81 |
| 4 | 2 | 33 | 0.87 |

df2:

| Index | x | y |
-------------------------
| 0 | 1 | 3 |
| 1 | 2 | 2 |
| 2 | 1 | 6 |


df_combined:

| Index | Wafer | Chip | Value | x | y |
-------------------------------------------------
| 0 | 1 | 32 | 0.99 | 1 | 3 |
| 1 | 1 | 33 | 0.89 | 2 | 2 |
| 2 | 1 | 39 | 0.96 | 1 | 6 |
| 3 | 2 | 32 | 0.81 | 1 | 3 | <--- auto-repeats...
| 4 | 2 | 33 | 0.87 | 2 | 2 |

这是内置的连接/合并类型,还是需要某种循环?

{这只是虚假数据,但 dfs 超过 1000 行...}

当前代码是一个简单的外部合并,但不提供填充/重复结束:

df = main.merge(df_coords, left_index=True, right_index = True, how='outer') 并只给出 NaN。

我检查过: Merge two python pandas data frames of different length but keep all rows in output data frame pandas: duplicate rows from small dataframe to large based on cell value

感觉这可能是合并函数中某个地方的争论......但我找不到它。非常感谢任何帮助。

谢谢

最佳答案

您可以重复df2,直到它与df1一样长,然后reset_index合并:

new_len = round(len(df1)/len(df2))
repeated = (pd.concat([df2] * new_len)
.reset_index()
.drop(["index"], 1)
.iloc[:len(df1)])

repeated
x y
0 1 3
1 2 2
2 1 6
3 1 3
4 2 2

df1.merge(repeated, how="outer", left_index=True, right_index=True)
Wafer Chip Value x y
0 1 32 0.99 1 3
1 1 33 0.89 2 2
2 1 39 0.96 1 6
3 2 32 0.81 1 3
4 2 33 0.87 2 2

有点hacky,但应该可以。

注意:我假设您的 Index 列实际上不是列,但实际上旨在表示数据框索引。我做出这个假设是因为您在 merge() 代码中引用了 left_index/right_index args。如果 Index 实际上是它自己的列,则此代码基本上可以工作,如果不这样做,您只需要 drop Index希望它出现在最终的df中。

关于python - Pandas 合并或加入较小的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51705734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com