Copy pandas DataFrame row to several other rows

A simple and practical question, but I can not find a solution.

The questions I looked at were as follows:

Changing a subset of strings in a pandas frame

Changing specific values ​​in multiple pandas DataFrame columns at once

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

Selection with complex criteria from pandas.DataFrame

The key difference between them and mine is that I do not need to insert a single value, but a string.

My problem is that I take the data frame row, say df1 . So I have a series.

Now I have another data file, df2 , that I have selected several rows according to the criteria, and I want to replicate this series to all these rows.

df1:

 Index/Col ABC 1 0 0 0 2 0 0 0 3 1 2 3 4 0 0 0 

df2:

 Index/Col ABC 1 0 0 0 2 0 0 0 3 0 0 0 4 0 0 0 

What I want to do is insert df1 [3] into the lines df2 [2] and df3 [3], for example. So, something like broken code:

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

return

df2:

 Index/Col ABC 1 0 0 0 2 1 2 3 3 1 2 3 4 0 0 0 
+5
source share
2 answers

Use loc and pass the list of indices of interest, after the following comma : indicates that we want to set all the column values, then we assign a series, but call the .values attribute to make it a numpy array. Otherwise, you will get a ValueError , because there will be a form mismatch, since you intend to overwrite 2 lines with one line, and if it is Series , then it will not be aligned as you wish:

 In [76]: df2.loc[[2,3],:] = df1.loc[3].values df2 Out[76]: ABC 1 0 0 0 2 1 2 3 3 1 2 3 4 0 0 0 
+7
source

Suppose you need to copy specific rows and columns from a dataframe into another data frame. 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 
0
source

Source: https://habr.com/ru/post/1247987/


All Articles