假设我有一个包含 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 value
0 0 0.496714
1 1 -0.138264
2 2 0.647689
3 3 1.523030
4 4 -0.234153
5 5 -0.234137
6 6 1.579213
7 7 0.767435
8 8 -0.469474
9 9 0.542560
我想将这个系列映射到这个数据框:
uniq = pd.Series([1,3,5,6], index=[20, 45, 47, 51], name="unique_col")
# uniq
20 1
45 3
47 5
51 6
Name: 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"]
# myresult
20 -0.138264
45 1.523030
47 -0.234137
51 1.579213
Name: value, dtype: float64
有这个必要吗?有没有更简单的方法,不涉及pd.merge
和从Series
到DataFrame
的转换?
最佳答案
这是您需要的吗?
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
关于python - Pandas 通过数据框的 2 列将一个系列映射到另一个系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55797448/