簡體   English   中英

如何使用一系列列名從 pandas dataframe 獲取系列?

[英]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])

如何使用sdf進行切片並獲取另一個系列s1 ,其中包含與s中的(index, value)對對應的df值作為df中的.loc()標識符,即

s1 = pd.Series(index=[0, 1, 2], data=[1, 5, 9])

使用DataFrame.lookup根據s.indexsdf中查找值,然后從此查找值創建一個新系列:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM