为了账号安全,请及时绑定邮箱和手机立即绑定

熊猫通过数据框的 2 列将一个系列映射到另一个系列

熊猫通过数据框的 2 列将一个系列映射到另一个系列

蝴蝶刀刀 2022-01-18 17:25:55
假设我有一个包含 2 列的数据框:indexes = pd.Series(np.arange(10))np.random.seed(seed=42)values = pd.Series(np.random.normal(size=10))df = pd.DataFrame({"unique_col": indexes, "value": values})# df:   unique_col     value0           0  0.4967141           1 -0.1382642           2  0.6476893           3  1.5230304           4 -0.2341535           5 -0.2341376           6  1.5792137           7  0.7674358           8 -0.4694749           9  0.542560我想把这个系列映射到这个数据框:uniq = pd.Series([1,3,5,6], index=[20, 45, 47, 51], name="unique_col")# uniq20    145    347    551    6Name: unique_col, dtype: int64该uniq系列有我不想失去的特殊索引。unique_col在int这里,但在我的现实世界中,它是一个复杂而独特的字符串。我想映射unique_col并提取value,我目前这样做:uniqdf = pd.DataFrame(uniq)mergedf = pd.merge(uniqdf, df, on="unique_col", how="left").set_index(uniq.index)myresult = mergedf["value"]# myresult20   -0.13826445    1.52303047   -0.23413751    1.579213Name: value, dtype: float64这是必要的吗?有没有更简单的方法不涉及pd.merge和从Seriesto转换DataFrame?
查看完整描述

2 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

这是你需要的吗?


s=df.set_index('unique_col').value.reindex(uniq).values

pd.Series(s,index=uniq.index)

Out[147]: 

20   -0.138264

45    1.523030

47   -0.234137

51    1.579213

dtype: float64


查看完整回答
反对 回复 2022-01-18
?
隔江千里

TA贡献1906条经验 获得超10个赞

只需使用map:


uniq.map(df.set_index('unique_col')['value'])

20   -0.138264

45    1.523030

47   -0.234137

51    1.579213

Name: unique_col, dtype: float64


查看完整回答
反对 回复 2022-01-18
  • 2 回答
  • 0 关注
  • 142 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信