📜  Python|熊猫系列.append()

📅  最后修改于: 2022-05-13 01:55:27.703000             🧑  作者: Mango

Python|熊猫系列.append()

Pandas 系列是带有轴标签的一维 ndarray。标签不必是唯一的,但必须是可散列的类型。该对象支持基于整数和基于标签的索引,并提供了许多用于执行涉及索引的操作的方法。

Pandas Series.append()函数用于连接两个或多个系列对象。

示例 #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 对象的末尾,并且它也忽略了索引。