使用来自另一个数据框的索引替换数据框中的行

时间:2020-05-07 17:44:50

标签: python pandas

我有两个具有相同结构dfdf_a的数据框。 df_adf的子集,我需要重新整合到df中。本质上,df_a具有df中经过处理的各种行(具有不同的索引)。

下面是每个dfdf_a的索引的示例。它们都具有相同的列结构,因此所有列都相同,只是行和行的等式不同。

>> df
index  ..  other_columns  ..
0   
1
2
3
. .
9999
10000
10001

[10001 rows x 20 columns]

>> df_a
index  ..  other_columns  ..
5
12
105
712
. .
9824
9901
9997

[782 rows x 20 columns]

因此,我只想覆盖df中索引为df_a的行以及df_a中的相应行。我签出了Replace rows in a Pandas df with rows from another dfreplace rows in a pandas data frame,但都没有告诉我们如何使用另一个数据框的索引来替换行中的值。

2 个答案:

答案 0 :(得分:1)

类似的东西:

df.loc[df_a.index, :] = df_a[:]

答案 1 :(得分:0)

我不知道这是否意味着您的意思,因为您需要更具体,但是如果将第一个数据帧修改为具有不同索引的新数据帧,则可以使用此代码重置返回索引:

import pandas as pd

df_a = pd.DataFrame({'a':[1,2,3,4],'b':[5,4,2,7]}, index=[2,55,62,74])
df_a.reset_index(inplace=True, drop=True)
print(df_a)

PRINTS:
   a  b
0  1  5
1  2  4
2  3  2
3  4  7