gpt4 book ai didi

python - 如何在 Python 中迭代 2 个 DataFrame 并填充一列

转载 作者:行者123 更新时间:2023-11-30 22:17:00 26 4
gpt4 key购买 nike

例如,我有 2 个数据框:

df1:

index  A    C
3 a NaN
4 b NaN
6 c NaN
7 d NaN
9 e NaN
10 f NaN
12 g NaN
13 h NaN
15 i NaN
16 j NaN

df2(N作为索引):

N    Name
2 Tom
5 Jack
8 Rose
11 Marrie
14 Lucy

我想比较这两个 dfs 的索引值,并在 df1 中填写“C”列作为名称,如下所示:

   A  B   C
3 a Tom
4 b Tom
6 c Jack
7 d Jack
9 e Rose
10 f Rose
12 g Marrie
13 h Marrie
15 i Lucy
16 j Lucy

最佳答案

看来您需要merge_asof

#df1=df1.reset_index()
#df2=df2.reset_index()
pd.merge_asof(df1,df2,left_on='index',right_on='N').drop(['C','N'],1)
Out[143]:
index A Name
0 3 a Tom
1 4 b Tom
2 6 c Jack
3 7 d Jack
4 9 e Rose
5 10 f Rose
6 12 g Marrie
7 13 h Marrie
8 15 i Lucy
9 16 j Lucy

关于python - 如何在 Python 中迭代 2 个 DataFrame 并填充一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49784079/

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