如何从 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
以上是 如何从 Pandas 中的另一个 DataFrame 添加列? 的全部内容, 来源链接: utcz.com/z/351625.html