如何从 Pandas 中的另一个 DataFrame 添加列?
该insert()方法用于从另一个DataFrame添加一列。首先,让我们创建我们的第一个DataFrame-
dataFrame1 = pd.DataFrame({"Car": ["Audi","Lamborghini", "BMW", "Lexus"], "Place": ["US", "UK", "India", "Australia"], "Units": [200, 500, 800, 1000]})
现在,让我们创建我们的第二个DataFrame-
dataFrame2 = pd.DataFrame({"Model": [2018, 2019, 2020, 2021], "CC": [3000, 2800, 3500, 3300]})
从DataFrame1添加到DataFrame2的Car列
# Car column to be added to the second dataframe fetched_col = dataFrame1["Car"]
示例
以下是代码-
import pandas as pd dataFrame1 = pd.DataFrame({"Car": ["Audi", "Lamborghini", "BMW", "Lexus"], "Place": ["US", "UK", "India", "Australia"], "Units": [200, 500, 800, 1000]}) print("数据框1...") print(dataFrame1) dataFrame2 = pd.DataFrame({"Model": [2018, 2019, 2020, 2021], "CC": [3000, 2800, 3500, 3300]}) print("数据框2...") print(dataFrame2) # Car column to be added to the second dataframe fetched_col = dataFrame1["Car"] dataFrame2.insert(1, "LuxuryCar", fetched_col) print("Dataframe 2 (Updated):") print(dataFrame2)输出结果
这将产生以下输出-
数据框1... Car Place Units 0 Audi US 200 1 Lamborghini UK 500 2 BMW India 800 3 Lexus Australia 1000 数据框2... CC Model 0 3000 2018 1 2800 2019 2 3500 2020 3 3300 2021 Dataframe 2 (Updated): CC LuxuryCar Model 0 3000 Audi 2018 1 2800 Lamborghini 2019 2 3500 BMW 2020 3 3300 Lexus 2021