Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding row from one dataframe to another

Tags:

python

pandas

I am trying to insert or add from one dataframe to another dataframe. I am going through the original dataframe looking for certain words in one column. When I find one of these terms I want to add that row to a new dataframe.

I get the row by using. entry = df.loc[df['A'] == item] But when trying to add this row to another dataframe using .add, .insert, .update or other methods i just get an empty dataframe.

I have also tried adding the column to a dictionary and turning that into a dataframe but it writes data for the entire row rather than just the column value. So is there a way to add one specific row to a new dataframe from my existing variable ?

like image 314
user1365234 Avatar asked Aug 15 '19 03:08

user1365234


People also ask

How do I add a row from one DataFrame to another?

append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object. Columns not in the original dataframes are added as new columns and the new cells are populated with NaN value.

How do I add a column from one DataFrame to another?

After extraction, the column needs to be simply added to the second dataframe using join() function. This function needs to be called with reference to the dataframe in which the column has to be added and the variable name which stores the extracted column name has to be passed to it as the argument.

How do I add a row to a DataFrame list?

By using df. loc[index]=list you can append a list as a row to the DataFrame at a specified Index, In order to add at the end get the index of the last record using len(df) function. The below example adds the list ["Hyperion",27000,"60days",2000] to the end of the pandas DataFrame. Yields below output.

How do you append a data frame?

Dataframe append syntax Using the append method on a dataframe is very simple. You type the name of the first dataframe, and then . append() to call the method. Then inside the parenthesis, you type the name of the second dataframe, which you want to append to the end of the first.


1 Answers

So the entry is a dataframe containing the rows you want to add? you can simply concatenate two dataframe using concat function if both have the same columns' name

import pandas as pd

entry = df.loc[df['A'] == item]
concat_df = pd.concat([new_df,entry])

pandas.concat reference:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html

like image 112
CHOCOLEO Avatar answered Sep 20 '22 17:09

CHOCOLEO