Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy pandas DataFrame row to multiple other rows

Tags:

python

pandas

Simple and practical question, yet I can't find a solution.

The questions I took a look were the following:

Modifying a subset of rows in a pandas dataframe

Changing certain values in multiple columns of a pandas DataFrame at once

Fastest way to copy columns from one DataFrame to another using pandas?

Selecting with complex criteria from pandas.DataFrame

The key difference between those and mine is that I need not to insert a single value, but a row.

My problem is, I pick up a row of a dataframe, say df1. Thus I have a series.

Now I have this other dataframe, df2, that I have selected multiple rows according to a criteria, and I want to replicate that series to all those row.

df1:

Index/Col   A   B  C
1           0   0  0
2           0   0  0
3           1   2  3
4           0   0  0

df2:

Index/Col   A   B  C
1           0   0  0
2           0   0  0
3           0   0  0
4           0   0  0

What I want to accomplish is inserting df1[3] into the lines df2[2] and df3[3] for example. So something like the non working code:

series = df1[3]
df2[df2.index>=2 and df2.index<=3] = series

returning

df2:

Index/Col   A   B  C
1           0   0  0
2           1   2  3
3           1   2  3
4           0   0  0
like image 319
Pedro Braz Avatar asked Apr 26 '16 21:04

Pedro Braz


2 Answers

Use loc and pass a list of the index labels of interest, after the following comma the : indicates we want to set all column values, we then assign the series but call attribute .values so that it's a numpy array. Otherwise you will get a ValueError as there will be a shape mismatch as you're intending to overwrite 2 rows with a single row and if it's a Series then it won't align as you desire:

In [76]:
df2.loc[[2,3],:] = df1.loc[3].values
df2

Out[76]:
   A  B  C
1  0  0  0
2  1  2  3
3  1  2  3
4  0  0  0
like image 52
EdChum Avatar answered Sep 18 '22 13:09

EdChum


Suppose you have to copy certain rows and columns from dataframe to some another data frame do this. code

    df2 = df.loc[x:y,a:b]   // x and y are rows bound and a and b are column 
                                bounds that you have to select
like image 29
Ayush Srivastava Avatar answered Sep 17 '22 13:09

Ayush Srivastava