Python pandas adding row

How to Add or Append Row to Pandas DataFrame?

To append or add a row to DataFrame, create the new row as Series and use DataFrame.append() method.

In this tutorial, we shall learn how to append a row to an existing DataFrame, with the help of illustrative example programs.

Syntax of append()

The syntax of DataFrame.append() function to append a row new_row to the DataFrame mydataframe is

mydataframe.append(new_row, ignore_index=True)

where the resulting DataFrame contains new_row added to mydataframe.

append() is immutable. It does not change the original DataFrame, but returns a new DataFrame created from the given DataFrame with the row appended. In order to update the original DataFrame, assign the DataFrame returned by the append() function back to the original DataFrame.

mydataframe = mydataframe.append(new_row, ignore_index=True)

Examples

1. Add Row to DataFrame

In this example, we will create a DataFrame and append a new row to this DataFrame. The new row is initialized as a Python Dictionary and append() function is used to append the row to the dataframe.

When you are adding a Python Dictionary to append(), make sure that you pass ignore_index=True.

Читайте также:  Php функция текущего времени

The append() method returns the dataframe with the newly added row.

Python Program

import pandas as pd data = #create dataframe df_marks = pd.DataFrame(data) print('Original DataFrame\n------------------') print(df_marks) new_row = #append row to the dataframe df_marks = df_marks.append(new_row, ignore_index=True) print('\n\nNew row added to DataFrame\n--------------------------') print(df_marks)

Run the above Python program, and you shall see the original dataframe, and the dataframe appended with the new row.

Original DataFrame ------------------ name physics chemistry algebra 0 Somu 68 84 78 1 Kiku 74 56 88 2 Amol 77 73 82 3 Lini 78 69 87 New row added to DataFrame -------------------------- name physics chemistry algebra 0 Somu 68 84 78 1 Kiku 74 56 88 2 Amol 77 73 82 3 Lini 78 69 87 4 Geo 87 92 97

2. Add Row to Pandas DataFrame (ignoreIndex = False)

If you do not provide the parameter ignoreIndex=False, you will get TypeError.

In the following example, we will try to append a row to DataFrame with the parameter ignoreIndex=False.

Python Program

import pandas as pd data = #create dataframe df_marks = pd.DataFrame(data) print('Original DataFrame\n------------------') print(df_marks) new_row = #append row to the dataframe df_marks = df_marks.append(new_row, ignore_index=False) print('\n\nNew row added to DataFrame\n--------------------------') print(df_marks)
Original DataFrame ------------------ name physics chemistry 0 Amol 77 73 1 Lini 78 85 Traceback (most recent call last): File "example1.py", line 14, in df_marks = df_marks.append(new_row, ignore_index=False) File "C:\Users\PythonExamples\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\frame.py", line 6658, in append raise TypeError('Can only append a Series if ignore_index=True' TypeError: Can only append a Series if ignore_index=True or if the Series has a name

As the error message says, we need to either provide the parameter ignore_index=True or append the row, that is Series with a name.

We have already seen in Example 1, how to add row to the DataFrame with ignore_index=True. Now we will see how to add a row with ignore_index=False.

Python Program

import pandas as pd data = #create dataframe df_marks = pd.DataFrame(data) print('Original DataFrame\n------------------') print(df_marks) new_row = pd.Series(data=, name='x') #append row to the dataframe df_marks = df_marks.append(new_row, ignore_index=False) print('\n\nNew row added to DataFrame\n--------------------------') print(df_marks)

We have named the Series as data. Therefore ignore_index=False does not return a TypeError and the row is appended to the DataFrame.

Original DataFrame ------------------ name physics chemistry 0 Amol 77 73 1 Lini 78 85 New row added to DataFrame -------------------------- name physics chemistry 0 Amol 77 73 1 Lini 78 85 x Geo 87 92

Summary

In this Pandas Tutorial, we have used append() function to add a new row to Pandas DataFrame.

Источник

Как добавить строки в фрейм данных Pandas (с примерами)

Вы можете использовать функцию df.loc() , чтобы добавить строку в конец кадра данных pandas:

#add row to end of DataFrame df.loc[ len(df.index )] = [value1, value2, value3, . ] 

И вы можете использовать функцию df.append() для добавления нескольких строк существующего DataFrame в конец другого DataFrame:

#append rows of *df2* to end of existing DataFrame df = df.append(df2, ignore_index = True ) 

В следующих примерах показано, как использовать эти функции на практике.

Пример 1: добавить одну строку в Pandas DataFrame

Следующий код показывает, как добавить одну строку в конец кадра данных pandas:

import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df points rebounds assists 0 10 7 11 1 12 7 8 2 12 8 10 3 14 13 6 4 13 7 6 5 18 4 5 #add new row to end of DataFrame df.loc[ len(df.index )] = [20, 7, 5] #view updated DataFrame df points rebounds assists 0 10 7 11 1 12 7 8 2 12 8 10 3 14 13 6 4 13 7 6 5 18 4 5 6 20 7 5 

Пример 2: добавить несколько строк в Pandas DataFrame

Следующий код показывает, как добавить несколько строк существующего DataFrame в конец другого DataFrame:

import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df points rebounds assists 0 10 7 11 1 12 7 8 2 12 8 10 3 14 13 6 4 13 7 6 5 18 4 5 #define second DataFrame df2 = pd.DataFrame() #add new row to end of DataFrame df = df.append(df2, ignore_index = True ) #view updated DataFrame df points rebounds assists 0 10 7 11 1 12 7 8 2 12 8 10 3 14 13 6 4 13 7 6 5 18 4 5 6 21 7 11 7 25 7 3 8 26 13 3 

Обратите внимание, что два кадра данных должны иметь одинаковые имена столбцов, чтобы успешно добавлять строки одного кадра данных в конец другого.

Источник

5 Easy Ways to Add Rows to a Pandas Dataframe

Top 5 Ways To Add Rows To Pandas DataFrame

In this Python tutorial, we are going to discuss the top five ways to add or insert one or multiple rows to the pandas DataFrame object. So, let’s get started with our discussion.

Methods to Add Rows to a Pandas Dataframe

Let’s first create a sample pandas DataFrame object to start with and then we will keep adding one or multiple rows to it using the following methods.

# Import pandas Python module import pandas as pd # Create a sample pandas DataFrame object df = pd.DataFrame() # Print the created pandas DataFrame print('Sample pandas DataFrame:\n') print(df)
Sample pandas DataFrame: RegNo Name CGPA Dept City 0 111 Gautam 8.85 ECE Jalandhar 1 112 Tanya 9.03 ICE Ranchi 2 113 Rashmi 7.85 IT Patna 3 114 Kirti 8.85 CSE Patiala 4 115 Ravi 9.45 CHE Rajgir

Method #1

Add a pandas Series object as a row to the existing pandas DataFrame object.

# Create a pandas Series object with all the column values passed as a Python list s_row = pd.Series([116,'Sanjay',8.15,'ECE','Biharsharif'], index=df.columns) # Append the above pandas Series object as a row to the existing pandas DataFrame # Using the DataFrame.append() function df = df.append(s_row,ignore_index=True) # Print the modified pandas DataFrame object after addition of a row print('Modified Sample pandas DataFrame:\n') print(df)
Modified Sample pandas DataFrame: RegNo Name CGPA Dept City 0 111 Gautam 8.85 ECE Jalandhar 1 112 Tanya 9.03 ICE Ranchi 2 113 Rashmi 7.85 IT Patna 3 114 Kirti 8.85 CSE Patiala 4 115 Ravi 9.45 CHE Rajgir 5 116 Sanjay 8.15 ECE Biharsharif

Method #2

Add a Python dictionary as a row to the existing pandas DataFrame object.

# Create a Python dictionary object with all the column values d_row = # Append the above Python dictionary object as a row to the existing pandas DataFrame # Using the DataFrame.append() function df = df.append(d_row,ignore_index=True) # Print the modified pandas DataFrame object after addition of a row print('Modified Sample pandas DataFrame:\n') print(df)
Modified Sample pandas DataFrame: RegNo Name CGPA Dept City 0 111 Gautam 8.85 ECE Jalandhar 1 112 Tanya 9.03 ICE Ranchi 2 113 Rashmi 7.85 IT Patna 3 114 Kirti 8.85 CSE Patiala 4 115 Ravi 9.45 CHE Rajgir 5 116 Sanjay 8.15 ECE Biharsharif 6 117 Sarthak 8.88 ECE Allahabad

NOTE: Please set the ignore_index parameter of the DataFrame.append() function to True while passing a Python dictionary or a pandas Series otherwise, it will throw an error.

Method #3

Add a Python list object as a row to the existing pandas DataFrame object using DataFrame.loc[] method.

# Create a Python list object with all the column values l_row = [118,"Kanika",7.88,"EE","Varanasi"] # Append the above Python list object as a row to the existing pandas DataFrame # Using the DataFrame.loc[] df.loc[7] = l_row # Print the modified pandas DataFrame object after addition of a row print('Modified Sample pandas DataFrame:\n') print(df)
Modified Sample pandas DataFrame: RegNo Name CGPA Dept City 0 111 Gautam 8.85 ECE Jalandhar 1 112 Tanya 9.03 ICE Ranchi 2 113 Rashmi 7.85 IT Patna 3 114 Kirti 8.85 CSE Patiala 4 115 Ravi 9.45 CHE Rajgir 5 116 Sanjay 8.15 ECE Biharsharif 6 117 Sarthak 8.88 ECE Allahabad 7 118 Kanika 7.88 EE Varanasi

Method #4

Add the rows of one pandas DataFrame object to another pandas DataFrame object using the DataFrame.append() function.

# Create a new pandas DataFrame object df2 = pd.DataFrame() # Print the newly created pandas DataFrame object print('New pandas DataFrame:\n') print(df2) # Append the rows of the above pandas DataFrame to the existing pandas DataFrame # Using the DataFrame.append() df = df.append(df2,ignore_index=True) # Print the modified pandas DataFrame object after addition of rows print('\nModified Sample pandas DataFrame:\n') print(df)
New pandas DataFrame: RegNo Name CGPA Dept City 0 119 Gaurav 8.85 ECE Jalandhar 1 120 Thaman 9.03 ICE Ranchi 2 121 Radha 7.85 IT Patna Modified Sample pandas DataFrame: RegNo Name CGPA Dept City 0 111 Gautam 8.85 ECE Jalandhar 1 112 Tanya 9.03 ICE Ranchi 2 113 Rashmi 7.85 IT Patna 3 114 Kirti 8.85 CSE Patiala 4 115 Ravi 9.45 CHE Rajgir 5 116 Sanjay 8.15 ECE Biharsharif 6 116 Sanjay 8.15 ECE Biharsharif 7 118 Kanika 7.88 EE Varanasi 8 119 Gaurav 8.85 ECE Jalandhar 9 120 Thaman 9.03 ICE Ranchi 10 121 Radha 7.85 IT Patna

Method #5

Add a row to the existing pandas DataFrame object at a specific index position using DataFrame.iloc[] method.

# Create a Python list object with all the column values i_row = [122,"Zahir",6.88,"ME","Kolkata"] # Append the above Python list object as a row to the existing pandas DataFrame # At index 2 using the DataFrame.iloc[] df.iloc[2] = i_row # Print the modified pandas DataFrame object after addition of a row print('Modified Sample pandas DataFrame:\n') print(df)
Modified Sample pandas DataFrame: RegNo Name CGPA Dept City 0 111 Gautam 8.85 ECE Jalandhar 1 112 Tanya 9.03 ICE Ranchi 2 122 Zahir 6.88 ME Kolkata 3 114 Kirti 8.85 CSE Patiala 4 115 Ravi 9.45 CHE Rajgir 5 116 Sanjay 8.15 ECE Biharsharif 6 116 Sanjay 8.15 ECE Biharsharif 7 118 Kanika 7.88 EE Varanasi 8 119 Gaurav 8.85 ECE Jalandhar 9 120 Thaman 9.03 ICE Ranchi 10 121 Radha 7.85 IT Patna

NOTE: Kindly take care while using the DataFrame.iloc[] method, as it replaces the existing row at that index position with the new row.

Conclusion

In this tutorial, We have learned the top five methods to add or insert one or multiple rows to an existing pandas DataFrame object. Hope you have understood the things discussed above well and are ready to use these methods in your own data analysis project. Thanks for reading! Stay tuned with us for more exciting learning resources on Python programming.

Источник

Оцените статью