Python – Pandas dataframe.append()
Python是一种进行数据分析的伟大语言,主要是因为以数据为中心的Python软件包的奇妙生态系统。Pandas _是这些包中的一个,使导入和分析数据变得更加容易。Pandas dataframe.append()函数用于将其他数据框架的行附加到给定数据框架的末尾,返回一个新的数据框架对象。原数据框架中没有的列被添加为新的列,新的单元格被填充为NaN值。
语法:
DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None)
参数:
- other:数据框架或系列/数据类对象,或这些对象的列表
- ignore_index : 如果为真,不使用索引标签。
- verify_integrity : 如果为真,在创建有重复的索引时引发ValueError。
- sort : 如果self和other的列没有对齐,则对列进行排序。默认的排序方式已被废弃,在未来的pandas版本中会改为不排序。明确地传递sort=True来消除警告和排序。明确传入sort=False以消除警告并不进行排序。
返回类型:附加的。数据框架
实例#1:创建两个数据框,并将第二个数据框追加到第一个数据框。
# Importing pandas as pd
import pandas as pd
# Creating the first Dataframe using dictionary
df1 = df = pd.DataFrame({"a":[1, 2, 3, 4],
"b":[5, 6, 7, 8]})
# Creating the Second Dataframe using dictionary
df2 = pd.DataFrame({"a":[1, 2, 3],
"b":[5, 6, 7]})
# Print df1
print(df1, "\n")
# Print df2
df2
输出:
现在将df2附加在df1的末尾。
# to append df2 at the end of df1 dataframe
df1.append(df2)
输出:
注意第二个数据框的索引值在附加的数据框中被保留。如果我们不希望它发生,那么我们可以设置ignore_index=True。
# A continuous index value will be maintained
# across the rows in the new appended data frame.
df1.append(df2, ignore_index = True)
例子#2:附加不同形状的数据框。对于数据框中不等的列数,其中一个数据框中不存在的值将被填充为NaN值。
# Importing pandas as pd
import pandas as pd
# Creating the first Dataframe using dictionary
df1 = pd.DataFrame({"a":[1, 2, 3, 4],
"b":[5, 6, 7, 8]})
# Creating the Second Dataframe using dictionary
df2 = pd.DataFrame({"a":[1, 2, 3],
"b":[5, 6, 7],
"c":[1, 5, 4]})
# for appending df2 at the end of df1
df1 = df1.append(df2, ignore_index = True)
df1
输出:
注意,新的单元格是用NaN值填充的。