简体   繁体   中英

Replace a subset of rows of dataframe A with rows of dataframe B in python pandas

I'm trying to replace the values in the rows 500 to 750 in column col1 in dataframe df_A with the values column col1 of dataframe df_B (with altogether 250 rows) in Python Pandas.

I tried doing it like this

df_A.col1.iloc[500:750] = df_B.col1

But this yields the notorious

A value is trying to be set on a copy of a slice from a DataFrame

and the values in df_A.col1.iloc[500:750] get replaced by NaN s . So how can I do this kind of replacement of several rows with rows from another dataframe in Pandas without using a for-loop?

Try to use loc instead:

import pandas as pd
df=pd.DataFrame(np.arange(15).reshape(5,3), columns=['a0','a1','a2'])
dg=pd.DataFrame(np.arange(9).reshape(3,3), columns=['b0','b1','b2'])
print('df=', df)
print('\ndg=', dg)

#replacement of [5,8,11] by [1,4,7]
df.loc[1:3, 'a2']=dg.b1.values
print("\ndf (after replacement) \n ",df)
df=    a0  a1  a2
0   0   1   2
1   3   4   5
2   6   7   8
3   9  10  11
4  12  13  14

dg=    b0  b1  b2
0   0   1   2
1   3   4   5
2   6   7   8

df (after replacement) 
     a0  a1  a2
0   0   1   2
1   3   4   1
2   6   7   4
3   9  10   7
4  12  13  14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM