[英]How to get a series from a pandas dataframe using a series of column names?
我有一個帶有數字數據的 pandas dataframe df
。 我還有一個系列s
,其索引與df
相同,值由df
列標簽組成,例如
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])
如何使用s
對df
進行切片並獲取另一個系列s1
,其中包含與s
中的(index, value)
對對應的df
值作為df
中的.loc()
標識符,即
s1 = pd.Series(index=[0, 1, 2], data=[1, 5, 9])
使用DataFrame.lookup
根據s.index
和s
在df
中查找值,然后從此查找值創建一個新系列:
s1 = pd.Series(df.lookup(s.index, s), index=s.index)
使用DataFrame.stack
和使用DataFrame.loc
索引的另一個想法:
s1 = df.stack().loc[zip(s.index, s)].droplevel(1)
結果:
print(s1)
0 1
1 5
2 9
dtype: int64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.