Python Pandas Series.append()
Pandas系列是一个带有轴标签的一维ndarray。标签不需要是唯一的,但必须是一个可散列的类型。该对象支持基于整数和标签的索引,并提供了大量的方法来执行涉及索引的操作。
Pandas Series.append()函数用于连接两个或多个系列对象。
语法: Series.append(to_append, ignore_index=False, verify_integrity=False)
参数:
to_append :系列或系列的列表/tuple。
ignore_index : 如果为真,不使用索引标签。
verify_integrity : 如果为真,在创建有重复的索引时引发异常。
返回 : 附注:系列
示例#1:使用Series.append()函数将传递的系列对象追加到该系列对象的末尾。
# importing pandas as pd
import pandas as pd
# Creating the first Series
sr1 = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio'])
# Create the first Index
index_1 = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']
# set the index of first series
sr1.index = index_1
# Creating the second Series
sr2 = pd.Series(['Chicage', 'Shanghai', 'Beijing', 'Jakarta', 'Seoul'])
# Create the second Index
index_2 = ['City 6', 'City 7', 'City 8', 'City 9', 'City 10']
# set the index of second series
sr2.index = index_2
# Print the first series
print(sr1)
# Print the second series
print(sr2)
输出 :
City 1 New York
City 2 Chicago
City 3 Toronto
City 4 Lisbon
City 5 Rio
dtype: object
City 6 Chicage
City 7 Shanghai
City 8 Beijing
City 9 Jakarta
City 10 Seoul
dtype: object
现在我们将使用Series.append()函数将sr2追加到sr1系列的末尾。
# append sr2 at the end of sr1
result = sr1.append(sr2)
# Print the result
print(result)
输出 :
City 1 New York
City 2 Chicago
City 3 Toronto
City 4 Lisbon
City 5 Rio
City 6 Chicage
City 7 Shanghai
City 8 Beijing
City 9 Jakarta
City 10 Seoul
dtype: object
正如我们在输出中看到的,Series.append()函数已经成功地将sr2对象附加到sr1对象的末尾。
示例#2:使用Series.append()函数将传递的系列对象追加到这个系列对象的末尾。忽略这两个系列对象的原始索引。
# importing pandas as pd
import pandas as pd
# Creating the first Series
sr1 = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio'])
# Create the first Index
index_1 = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']
# set the index of first series
sr1.index = index_1
# Creating the second Series
sr2 = pd.Series(['Chicage', 'Shanghai', 'Beijing', 'Jakarta', 'Seoul'])
# Create the second Index
index_2 = ['City 6', 'City 7', 'City 8', 'City 9', 'City 10']
# set the index of second series
sr2.index = index_2
# Print the first series
print(sr1)
# Print the second series
print(sr2)
输出 :
City 1 New York
City 2 Chicago
City 3 Toronto
City 4 Lisbon
City 5 Rio
dtype: object
City 6 Chicage
City 7 Shanghai
City 8 Beijing
City 9 Jakarta
City 10 Seoul
dtype: object
现在我们将使用Series.append()函数将sr2追加到sr1系列的末尾。我们将忽略给定系列对象的索引。
# append sr2 at the end of sr1
# ignore the index
result = sr1.append(sr2, ignore_index = True)
# Print the result
print(result)
输出 :
0 New York
1 Chicago
2 Toronto
3 Lisbon
4 Rio
5 Chicage
6 Shanghai
7 Beijing
8 Jakarta
9 Seoul
dtype: object
正如我们在输出中看到的,Series.append()函数已经成功地将sr2对象追加到sr1对象的末尾,并且它还忽略了索引。