如何在 Pandas 中合并数据框?
要合并 Pandas 中的数据框,我们将展示一些示例。我们可以轻松地在 Pandas 中合并 DataFrame 甚至 Series。Pandas 是一个开源 Python 库,使用其强大的数据结构提供高性能数据处理和分析工具。数据框是一种二维数据结构,即数据以表格形式排列在行和列中。
使用内连接合并 DataFrame
示例
让我们使用 Python 中的内连接合并数据框
import pandas as pd # Create Dictionaries dct1 = {'Player':['Jacob','Steve','David','John','Kane'], 'Age':[29, 25, 31, 26, 27]} dct2 = {'Rank':[1,2,3,4,5], 'Points':[100,87, 80,70, 50]} # Create DataFrame from Dictionary elements using pandas.dataframe() df1 = pd.DataFrame(dct1) df2 = pd.DataFrame(dct2) print("DataFrame1 = \n",df1) print("\nDataFrame2 = \n",df2) # Combining DataFrames using inner join res = pd.concat([df1, df2], axis=1, join='inner') print("\nCombined DataFrames = \n",res)
输出
DataFrame1 = Player Age 0 Jacob 29 1 Steve 25 2 David 31 3 John 26 4 Kane 27 DataFrame2 = Rank Points 0 1 100 1 2 87 2 3 80 3 4 70 4 5 50 Combined DataFrames = Player Age Rank Points 0 Jacob 29 1 100 1 Steve 25 2 87 2 David 31 3 80 3 John 26 4 70 4 Kane 27 5 50
使用 append() 合并 DataFrame
示例
在此示例中,我们将使用 Python 中的 append() 合并数据框
import pandas as pd # Create Dictionaries dct1 = {'Player':['Steve','David'], 'Age':[29, 25,]} dct2 = {'Player':['John','Kane'], 'Age':[31, 27]} # Create DataFrame from Dictionary elements using pandas.dataframe() df1 = pd.DataFrame(dct1) df2 = pd.DataFrame(dct2) print("DataFrame1 = \n",df1) print("\nDataFrame2 = \n",df2) # Combining DataFrames using append() res = df1.append(df2) print("\nCombined DataFrames = \n",res)
输出
DataFrame1 = Player Age 0 Steve 29 1 David 25 DataFrame2 = Player Age 0 John 31 1 Kane 27 Combined DataFrames = Player Age 0 Steve 29 1 David 25 0 John 31 1 Kane 27
使用 concat() 合并 DataFrame
示例
在此示例中,我们将使用 Python 中的 concat() 合并数据框 –
import pandas as pd # Create Dictionaries dct1 = {'Player':['Steve','David'], 'Age':[29, 25,]} dct2 = {'Player':['John','Kane'], 'Age':[31, 27]} # Create DataFrame from Dictionary elements using pandas.dataframe() df1 = pd.DataFrame(dct1) df2 = pd.DataFrame(dct2) print("DataFrame1 = \n",df1) print("\nDataFrame2 = \n",df2) # Combining DataFrames using concat() res = pd.concat([df1, df2]) print("\nCombined DataFrames = \n",res)
输出
DataFrame1 = Player Age 0 Steve 29 1 David 25DataFrame2 = Player Age 0 John 31 1 Kane 27 Combined DataFrames = Player Age 0 Steve 29 1 David 25 0 John 31 1 Kane 27
广告