如何在 pandas 中合并两个或多个系列(附示例)
您可以使用以下语法将两个或多个系列快速合并到单个 pandas DataFrame 中:
df = pd. concat ([series1, series2, ...], axis= 1 )
以下示例展示了如何在实践中使用此语法。
示例 1:合并 Pandas 中的两个系列
以下代码显示了如何将两个 pandas Series 合并到一个 pandas DataFrame 中:
import pandas as pd #define series series1 = pd. Series (['Mavs', 'Rockets', 'Spurs'], name=' Team ') series2 = pd. Series ([109, 103, 98], name=' Points ') #merge series into DataFrame df = pd. concat ([series1, series2], axis= 1 ) #view DataFrame df Team Points 0 Mavs 109 1 Rockets 103 2 Spurs 98
请注意,如果一个系列比另一个系列长,pandas 将自动为生成的 DataFrame 中的缺失值提供 NaN 值:
import pandas as pd #define series series1 = pd. Series (['Mavs', 'Rockets', 'Spurs'], name=' Team ') series2 = pd. Series ([109, 103], name=' Points ') #merge series into DataFrame df = pd. concat ([series1, series2], axis= 1 ) #view DataFrame df Team Points 0 Mavs 109 1 Rockets 103 2 Spurs NaN
示例 2:合并 Pandas 中的多个系列
以下代码显示了如何将多个系列合并到单个 pandas DataFrame 中:
import pandas as pd #define series series1 = pd. Series (['Mavs', 'Rockets', 'Spurs'], name=' Team ') series2 = pd. Series ([109, 103, 98], name=' Points ') series3 = pd. Series ([22, 18, 15], name=' Assists ') series4 = pd. Series ([30, 35, 28], name=' Rebounds ') #merge series into DataFrame df = pd. concat ([series1, series2, series3, series4], axis= 1 ) #view DataFrame df Team Points Assists Rebounds 0 Mavs 109 22 30 1 Rockets 103 18 35 2 Spurs 98 15 28
其他资源
如何合并索引上的两个 Pandas DataFrame
如何跨多列合并 Pandas DataFrame
如何堆叠多个 Pandas DataFrame