I have a pandas dataframe df with numeric data. I also have a series s with the same index as df and values consisting of df column labels, e.g.
import pandas as pd
df = pd.DataFrame(
index=[0, 1, 2], columns=[0, 1, 2],
data=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
)
s = pd.Series(index=[0, 1, 2]), data=[0, 1, 2])
How can I use s to slice df and get another series s1 that contains df values corresponding to the (index, value) pairs in s as their .loc() identifiers in df, i.e.
s1 = pd.Series(index=[0, 1, 2], data=[1, 5, 9])
Use DataFrame.lookup to lookup the values in df based on s.index and s, then create a new series from this lookup values:
s1 = pd.Series(df.lookup(s.index, s), index=s.index)
Another idea using DataFrame.stack and indexing using DataFrame.loc:
s1 = df.stack().loc[zip(s.index, s)].droplevel(1)
Result:
print(s1)
0 1
1 5
2 9
dtype: int64
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With