gpt4 book ai didi

python - 我将如何进行自定义 Pandas 数据框合并?

转载 作者:太空宇宙 更新时间:2023-11-03 12:35:30 25 4
gpt4 key购买 nike

假设我有:

data = [['tom', 10, 20], ['nick', 15, 30], ['juli', 14, 40]] 
df = pd.DataFrame(data, columns = ['Name', 'Low-Age', 'High-Age'])
print(df)
None
Name Low-Age High-Age
0 tom 10 20
1 nick 15 30
2 juli 14 40

然后我有另一个表:

data = [[10, 'school'], [30, 'college']] 
edu = pd.DataFrame(data, columns = ['Age', 'Education'])
print(edu)
None
Age Education
0 10 school
1 30 college

我怎样才能得到一张表,在该表中我可以将 edu['Age'] 与 df["Low-Age"] 或 df["High-Age"] 进行匹配。如果它们匹配,我想将 edu["Education"] 附加到 df. (假设 low-age 或 high-age 可以匹配,但不能同时匹配)

所以我希望我的输出是:

  Name  Low-Age  High-Age   Education
0 tom 10 20 school
1 nick 15 30 college
2 juli 14 40 NaN

最佳答案

堆栈 -> map

edu_dict = dict(zip(edu.Age, edu.Education))

Education = df[['Low-Age', 'High-Age']].stack().map(edu_dict).groupby(level=0).first()
df.assign(Education=Education)

Name Low-Age High-Age Education
0 tom 10 20 school
1 nick 15 30 college
2 juli 14 40 NaN

关于python - 我将如何进行自定义 Pandas 数据框合并?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58457800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com