Copy pandas DataFrame row to multiple other rows


Copy pandas DataFrame row to multiple other rows



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.


df1



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.


df2



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




2 Answers
2



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:


loc


:


.values


ValueError


Series


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





ok sounds right. Couple of questions, does the right side works if it is a series ? can you edit so that the conditional selection is taken into account ?
– Pedro Braz
Apr 26 '16 at 21:11





No, as I stated if you try that you get a ValueError shape mismatch. It would only work if you passed a Series of the same shape and if the index values matched
– EdChum
Apr 26 '16 at 21:11



ValueError


Series





o got it. Thanks !
– Pedro Braz
Apr 26 '16 at 21:15



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


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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to input without newline? (Python)

C++ thread error: no type named ‘type’ MINGW

Analog for TagView in flutter