Как добавить строку в dataframe pandas

от admin

pandas.DataFrame.append#

Append rows of other to the end of caller, returning a new object.

Deprecated since version 1.4.0: Use concat() instead. For further details see Deprecated DataFrame.append and Series.append

Columns in other that are not in the caller are added as new columns.

Parameters other DataFrame or Series/dict-like object, or list of these

The data to append.

ignore_index bool, default False

If True, the resulting axis will be labeled 0, 1, …, n — 1.

verify_integrity bool, default False

If True, raise ValueError on creating index with duplicates.

sort bool, default False

Sort columns if the columns of self and other are not aligned.

Changed in version 1.0.0: Changed to not sort by default.

A new DataFrame consisting of the rows of caller and the rows of other .

General function to concatenate DataFrame or Series objects.

If a list of dict/series is passed and the keys are all contained in the DataFrame’s index, the order of the columns in the resulting DataFrame will be unchanged.

Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once.

With ignore_index set to True:

The following, while not recommended methods for generating DataFrames, show two ways to generate a DataFrame from multiple data sources.

Добавление строки в Pandas DataFrame

Чтобы добавить или вставить строку в DataFrame, создайте новую строку, как Series и используйте метод append().

В этом руководстве мы узнаем, как добавить строку в существующий DataFrame с помощью наглядных примеров программ.

Синтаксис

Ниже приводится синтаксис функции DataFrame.appen().

Где, полученный DataFrame содержит new_row, добавленный в mydataframe.

append() не изменяет DataFrame, но возвращает новый с добавленной строкой.

Пример 1

В этом примере мы создадим DataFrame и добавим новую строку. Она инициализируется как словарь Python, а функция append() используется для добавления строки.

Когда вы добавляете словарь Python в append(), убедитесь, что вы передаете ignore_index = True.

Метод append() возвращает DataFrame с вновь добавленной строкой.

Запустите указанную выше программу Python, и вы увидите исходный DataFrame, к которому добавлена новая строка.

Пример 2

Если вы не укажете параметр ignoreIndex = False, вы получите TypeError.

В следующем примере мы попытаемся добавить строку в DataFrame с параметром ignoreIndex = False.

Как говорится в сообщении об ошибке, нам нужно либо предоставить параметр ignore_index = True, либо добавить строку, то есть Series, с именем.

Мы уже видели в примере 1, как добавить строку в DataFrame с ignore_index = True. Теперь посмотрим, как добавить строку с ignore_index = False.

Мы назвали серию данными. Поэтому ignore_index = False не возвращает TypeError, и строка добавляется к DataFrame.

В этом руководстве по Pandas мы использовали функцию append(), чтобы добавить строку в Pandas DataFrame.

How to Add / Insert a Row into a Pandas DataFrame

In this tutorial, you’ll learn how to add (or insert) a row into a Pandas DataFrame. You’ll learn how to add a single row, multiple rows, and at specific positions. You’ll also learn how to add a row using a list, a Series, and a dictionary.

By the end of this tutorial, you’ll have learned:

  • Different ways to add a single and multiple rows to a Pandas DataFrame
  • How to insert a row at particular positions, such as the top or bottom, of a Pandas DataFrame
  • How to add rows using lists, Pandas Series, and dictionaries

Table of Contents

Loading a Sample Pandas DataFrame

To follow along with this tutorial line-by-line, you can copy the code below into your favourite code editor. If you have your own data to follow along with, feel free to do so (though your results will, of course, vary):

We have four records and three different columns, covering a person’s Name, Age, and Location.

Add a Row to a Pandas DataFrame

The easiest way to add or insert a new row into a Pandas DataFrame is to use the Pandas .append() method. The .append() method is a helper method, for the Pandas concat() function. To learn more about how these functions work, check out my in-depth article here. In this section, you’ll learn three different ways to add a single row to a Pandas DataFrame.

Add a Row to a Pandas DataFrame Using a Dictionary

Let’s say that we wanted to add a new row containing the following data: <'Name':'Jane', 'Age':25, 'Location':'Madrid'>.

We could simply write:

In the example above, we were able to add a new row to a DataFrame using a dictionary. Because we passed in a dictionary, we needed to pass in the ignore_index=True argument.

Add a Row to a Pandas DataFrame Using a List

To add a list to a Pandas DataFrame works a bit differently since we can’t simply use the .append() function. In order to do this, we need to use the loc accessor. The label that we use for our loc accessor will be the length of the DataFrame. This will create a new row as shown below:

As a fun aside: using iloc is more challenging since it requires that the index position already exist – meaning we would need to either add an empty row first or overwrite data.

Add a Row to a Pandas DataFrame Using a Series

Now let’s try to add the same row as shown above using a Pandas Series, that we can create using a Python list. We simply pass a list into the Series() function to convert the list to a Series. Let’s see how this works:

Insert a Row to a Pandas DataFrame at the Top

Adding a row to the top of a Pandas DataFrame is quite simple: we simply reverse the options you learned about above. By this, I mean to say we append the larger DataFrame to the new row.

However, we must first create a DataFrame. We can do this using the pd.DataFrame() class. Let’s take a look:

Insert a Row to a Pandas DataFrame at a Specific Index

Adding a row at a specific index is a bit different. As shown in the example of using lists, we need to use the loc accessor. However, inserting a row at a given index will only overwrite this. What we can do instead is pass in a value close to where we want to insert the new row.

For example, if we have current indices from 0-3 and we want to insert a new row at index 2, we can simply assign it using index 1.5. Let’s see how this works:

This, of course, makes a few assumptions:

  1. Your index starts at 0. Adjust your loc index accordingly, if not.
  2. That your index can be mutated in this way. If your index is more meaningful, this may not be the case.

Insert Multiple Rows in a Pandas DataFrame

Adding multiple rows to a Pandas DataFrame is the same process as adding a single row. However, it can actually be much faster, since we can simply pass in all the items at once. For example, if we add items using a dictionary, then we can simply add them as a list of dictionaries.

Let’s take a look at an example:

Conclusion

In this tutorial, you learned how to add and insert rows into a Pandas DataFrame. You learned a number of different methods to do this, including using dictionaries, lists, and Pandas Series. You also learned how to insert new rows at the top, bottom, and at a particular index. Finally, you also learned how to add multiple rows to a Pandas DataFrame at the same time.

Читать:
Сколько раз выполнится цикл

Pandas Add Row to DataFrame – Definitive Guide

Pandas dataframe is a two-dimensional data structure.

You can add rows to the pandas dataframe using df.iLOC[i] = [‘col-1-value’, ‘col-2-value‘, ‘ col-3-value ‘] statement.

If you’re in Hurry

You can use the following to add rows to the dataframe.

  • It adds the rows to the dataframe using a dictionary.
  • It inserts the row at the end of the dataframe.

Code

Dataframe Will Look Like

Country First Name Last Name
0 India Vikram Aruchamy

If You Want to Understand Details, Read on…

In this tutorial, you’ll learn the different methods available to add rows to a dataframe. You’ll also learn how to insert a row into an empty dataframe.

Table of Contents

Creating an Empty Dataframe

First, you need to create an empty dataframe to add rows to it. You can do it by using DataFrame() method as shown below.

Code

An empty dataframe is created as df .

You can add rows to the dataframe using four methods. append() , concat() , iloc[] and loc[] .

Add row Using Append

The append() method appends a row to an existing dataframe.

Parameters

  • dictionary or Pandas Series or Dataframe – Object with values for new row
  • ignore_index = True Means the index from the series or the source dataframe will be ignored. The index available in the target dataframe will be used instead. False means otherwise. This is optional.

Returns

  • A resultant dataframe which has the rows from the target dataframe and a new row appended.

inplace append is not possible. Hence, do not forget to assign the result to a dataframe object to access it later.

In the following example,

  • a dictionary is created with values for the columns which already exist in the target dataframe.
  • It is appended to the target dataframe using the append() method.

Now, you’ve appended one row to the dataframe.

Dataframe Will Look Like

Country First Name Last Name
0 India Vikram Aruchamy

This is how you can insert a row to the dataframe using append.

Use this method when you want to add row to dataframe using dictionary or a pandas series.

Add row Using Concat

You can append a row to the dataframe using the concat() method. It concatenates two dataframe into one.

  • Create a dataframe with one row
  • Concatenate it to the existing dataframe.

Parameters

  • List of dataframes – List of dataframes that needs to be concatenated
  • ignore_index – Whether the index of the new dataframe should be ignored when concatenating to the target dataframe
  • axis = 0 – To denote that rows of the dataframe need to be converted.

Returns

  • It returns a new dataframe object which has the rows concatenated from two dataframes.

inplace concatenation is not supported. Hence, assign the result to a variable for later use.

Snippet

In the above example,

  • you’re creating a new dataframe with one row, and it is named df2 .
  • You’re concatenating this to dataframe df which already has one row in it.

Both df and df2 will be concatenated and you’ll see two rows in the resultant dataframe.

Dataframe Will Look Like

Country First Name Last Name
0 India Vikram Aruchamy
1 India Kumar Ram

Add row Using iLOC

You can use the iLoc[] attribute to add a row at a specific position in the dataframe.

  • iloc is an attribute for integer-based indexing used to select rows from the dataframe.
  • You can also use it to assign new rows at that position.

Adding a row at a specific index position will replace the existing row at that position.

When you’re using iLoc to add a row,

  • The dataframe must already have a row in the position. At least an empty row.
  • If a row is not available, you’ll see an error IndexError: iloc cannot enlarge its target object . iLoc will not expand the size of the dataframe automatically.

Code

In the following, a row is added at the index position 1 . It replaced the values available in that position with the new values.

Dataframe Will Look Like

Country First Name Last Name
0 India Vikram Aruchamy
1 India Shivam Pandey

This is how you can use the iloc[] to insert a row to the existing dataframe.

Use this method when you want to add rows at a specific position.

Add row Using LOC

loc[] attribute accesses a set of rows from the dataframe using the index label.

  • Assign rows with a specific index label using the loc attribute.
  • It’s not mandatory that a row already exists with a specific label. It’ll automatically extend the dataframe and add a row with that label, unlike the iloc[] method.

Code

To demonstrate loc using the row indexes with names like a , b ,

  • A new dataframe is created with labels a and b .
  • A new row is assigned with the row label c using the loc[] method.

First a dataframe df3 is created with two rows with label a and b . Then a row is inserted with the label c using the loc[] method.

Dataframe Will Look Like

This is how you can use the loc[] method to add rows to the dataframe. Either it is an empty dataframe, or it already has values.

Pandas Insert Empty Row

Empty rows can be appended by using the df.loc[df.shape[0]] and assigning None values for all the existing columns.

Code

For example, if your dataframe has three columns,

  • Create a series with 3 None values
  • Assign it to the last position of the dataframe.

An empty row is added at the end of the dataframe.

Dataframe Will Look Like

Country First Name Last Name
0 India Raj Kumar
1 India Vikram Aruchamy
2 India Shivam Pandey
3 India Shivam Pandey
4 India Krishna Kumar
5 None None None

This is how you can add an empty row to the end of the dataframe.

Why You Should Not Add Rows One By One To Dataframe

You may need to create a dataframe and append one row at a time in various scenarios.

In that case, it is advisable to create a list first to hold all the records and create a dataframe with all the records from the list in one shot using the pd.DataFrame() method.

Calling the append() method for each row is a costlier operation. But adding the rows to the list is not costlier. Hence, you can add to the list and create a dataframe using that list.

Code

For more details about this scenario, refer StackOverflow answer.

Dataframe Will Look Like

First Name Last Name Country
0 Krishna Kumar India
1 Ram Kumar India
2 Shivam Pandey India

This is how you can create a pandas dataframe by appending one row at a time.

Conclusion

To summarize, you’ve learned how to create empty dataframe in pandas and add rows to it using the append() , iloc[] , loc[] , concatenating two dataframes using concat() .

Похожие статьи