Добавить данные в пустой фрейм данных Pandas
Давайте посмотрим, как добавить данные в пустой фрейм данных Pandas.
Creating the Data Frame and assigning the columns to it
# importing the moduleimport pandas as pd # creating the DataFrame of int and floata = [[1, 1.2], [2, 1.4], [3, 1.5], [4, 1.8]]t = pd.DataFrame(a, columns =["A", "B"]) # displaying the DataFrameprint(t)print(t.dtypes) |
Выход :

При добавлении значений с плавающей запятой в столбец с типом данных с целым значением типовое преобразование результирующего столбца кадра данных в тип с плавающей запятой для размещения значения с плавающей запятой.
If we use the argument ignore_index = True => that the index values will remain continuous instead of starting again from 0, be default it’s value is False
# Appending a Data Frame of float and ints = pd.DataFrame([[1.3, 9]], columns = ["A", "B"])display(s) # makes index continuoust = t.append(s, ignore_index = True) display(t) # Resultant data frame is of type float and floatdisplay(t.dtypes) |
Выход :

When we appended the boolean format data into the data frame that was already of the type of float columns then it will change the values accordingly in order to accommodate the boolean values in the float data type domain only.
# Appending a Data Frame of bool and boolu = pd.DataFrame([[True, False]], columns =["A", "B"])display(u)display(u.dtypes) t = t.append(u)display(t)display(t.dtypes) # type casted into float and float |
Выход :

On appending the data of different data types to the previously formed Data Frame then the resultant Data Frame columns type will always be of the wider spectrum data type.
# Appending a Data Frame of object and objectx = pd.DataFrame([["1.3", "9.2"]], columns = ["A", "B"])display(x)display(x.dtypes) t = t.append(x)display(t)display(t.dtypes) |
Выход :

If we aim to create a data frame through a for loop then the most efficient way of doing that is as follows :
# Creating a DataFrame using a for loop in efficient mannery = pd.concat([pd.DataFrame([[i, i * 10]], columns = ["A", "B"]) for i in range(7, 10)], ignore_index = True) # makes index continuoust = t.append(y, ignore_index = True) display(t)display(t.dtypes) |
Выход

If we attempt to add different column than already in the data frame then results are as follows :
# Appending Different Columnsz = pd.DataFrame([["1.3", "9.2"]], columns = ["E", "F"])t = t.append(z)print(t)print(t.dtypes)print() |
Output :

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course