简体   繁体   中英

pandas map a series to another series by 2 columns of a dataframe

Let's say I have a dataframe with 2 columns:

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

And I want to map this series to this dataframe:

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

The uniq series have special index that I don't want to lose. unique_col is in int here but in my real world case it's a complex and unique string.

I want to map the unique_col and extract the value , I currently do it like this:

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

Is this necessary? Is there a simpler way that does not involve pd.merge and conversion from Series to DataFrame ?

Is this what you need ?

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

Just use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM