Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new line to existing pandas dataframe? [duplicate]

I have a pandas dataframe that has been defined as empty and then I would like to add some rows to it after doing some calculations.

I have tried to do the following:

test = pd.DataFrame(columns=['Name', 'Age', 'Gender'])

if #some statement:

test.append(['James', '95', 'M'])

If I try to print and then append to test shows

print(test)

test.append(['a', 'a', 'a', 'a', 'a', 'a'])

print(test)

>>>

Empty DataFrame
Columns: [Name, Age, Gender]
Index: []
Empty DataFrame
Columns: [Name, Age, Gender]
Index: []

So clearly the line is not being added to the dataframe.

I want the output to be

Name | Age | Gender
James | 95 | M
like image 762
user9940344 Avatar asked Jul 08 '19 09:07

user9940344


People also ask

How do you add duplicate rows in a DataFrame in Python?

duplicated() method is used to find duplicate rows in a DataFrame. It returns a boolean series which identifies whether a row is duplicate or unique. In this article, you will learn how to use this method to identify the duplicate rows in a DataFrame.

How do I add rows to an existing DataFrame?

We can also add multiple rows using the pandas. concat() by creating a new dataframe of all the rows that we need to add and then appending this dataframe to the original dataframe.

How do you append to 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.


2 Answers

Use append with dictionary as:

test = test.append(dict(zip(test.columns,['James', '95', 'M'])), ignore_index=True)

print(test)
    Name Age Gender
0  James  95      M
like image 88
Space Impact Avatar answered Oct 01 '22 06:10

Space Impact


Try to append it as dictionary:

>>> test = test.append({'Name': "James", "Age": 95, "Gender": "M"}, ignore_index=True)
>>> print(test)

Outputs:

    Name Age Gender
0  James  95      M
like image 35
Gahan Avatar answered Oct 01 '22 06:10

Gahan