簡體   English   中英

使用 Series 對象從數據框中選擇行(在 Python 中使用 Pandas)

[英]Use a Series object to select rows from a dataframe (in Python using Pandas)

我有一個如下所示的 Series 對象:

traffic_id_1    GEO03_D4T-RWS_I_6590A_V_0460A_ID_8481
traffic_id_2      GEO03_D4T-RWS_I_6590_V_0460_ID_1149
traffic_id_3              RWS01_MONIBAS_0351hrl0325ra
traffic_id_4              RWS01_MONIBAS_0351hrr0325ra
traffic_id_5              RWS01_MONIBAS_0351hrr0328ra
Name: 176, dtype: object

現在我想使用這個 Series 對象從包含這些 ID 的數據幀(它看起來像這樣)中選擇行。

TL;DR最基本的方法是什么?

額外信息:

我找到了這篇文章,這種方式似乎對我有用,但我正在學習一門課程,他們還沒有教我 .isin() 屬性。 這並不意味着我不能使用它,但我希望能夠僅使用我從課程中獲得的知識來使用它。

我在 Jupyter notebook 中工作並導入了 Pandas、matplotlib、matplotlib.pyplot 和 seaborn。

我不確定這是否對您有幫助,因為您似乎想根據您在課程中涵蓋的內容來做這件事,而我們無法訪問這些內容。 但是,在將相關 col 設置為索引后,您可以將系列和數據幀與reindex進行比較。

這是一個可重現的示例:

您的數據:

traffic_id_1    GEO03_D4T-RWS_I_6590A_V_0460A_ID_8481
traffic_id_2      GEO03_D4T-RWS_I_6590_V_0460_ID_1149
traffic_id_3              RWS01_MONIBAS_0351hrl0325ra
traffic_id_4              RWS01_MONIBAS_0351hrr0325ra
traffic_id_5              RWS01_MONIBAS_0351hrr0328ra

(復制到剪貼板,然后:)

# make series into df
df = pd.read_clipboard(header=None)
df.columns = ['a', 'b']
# pull out original series from df column
ser = pd.Series(df['b'].values, df['a'].values).copy()
# change some values in the original
df.loc[1, 'b'] = 'foo'
df.loc[3, 'b'] = 'bar'

所以數據框是:

    a               b
0   traffic_id_1    GEO03_D4T-RWS_I_6590A_V_0460A_ID_8481
1   traffic_id_2    foo
2   traffic_id_3    RWS01_MONIBAS_0351hrl0325ra
3   traffic_id_4    bar
4   traffic_id_5    RWS01_MONIBAS_0351hrr0328ra

以及系列:

traffic_id_1    GEO03_D4T-RWS_I_6590A_V_0460A_ID_8481
traffic_id_2      GEO03_D4T-RWS_I_6590_V_0460_ID_1149
traffic_id_3              RWS01_MONIBAS_0351hrl0325ra
traffic_id_4              RWS01_MONIBAS_0351hrr0325ra
traffic_id_5              RWS01_MONIBAS_0351hrr0328ra
dtype: object

# set index as relevant col
df = df.set_index('b')

df.reindex(ser).dropna()

輸出:

                                        a
GEO03_D4T-RWS_I_6590A_V_0460A_ID_8481   traffic_id_1
RWS01_MONIBAS_0351hrl0325ra             traffic_id_3
RWS01_MONIBAS_0351hrr0328ra             traffic_id_5

編輯:您也可以使用布爾過濾器實現此目的。 省略在數據框中設置索引的步驟:

mask = df.b == ser.reset_index(drop=True)
df[mask]

產生同樣的東西。 (或在一行中: df[df.b == ser.reset_index(drop=True)] )。 請注意,有必要去掉系列的唯一索引,使其與數據幀的索引對齊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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