簡體   English   中英

我如何 select Pandas DataFrame 中每一行的特定列?

[英]How can I select a specific column from each row in a Pandas DataFrame?

我有一個 DataFrame 格式如下:

    a   b   c
0   1   2   3
1   4   5   6
2   7   8   9
3   10  11  12
4   13  14  15

和這樣的數組,列名:

['a', 'a', 'b', 'c', 'b']

我希望提取一組數據,每行一個值。 列名數組指定每行中我想要的列。 在這里,結果將是:

[1, 4, 8, 12, 14]

這是否可以作為 Pandas 的單個命令,還是我需要迭代? 我嘗試使用索引

i = pd.Index(['a', 'a', 'b', 'c', 'b'])
i.choose(df)

但是我遇到了一個段錯誤,因為缺少文檔而無法診斷。

您可以使用lookup ,例如

>>> i = pd.Series(['a', 'a', 'b', 'c', 'b'])
>>> df.lookup(i.index, i.values)
array([ 1,  4,  8, 12, 14])

如果需要,其中i.index可能與range(len(i))不同。

對於大型數據集,如果准備將列名轉換為數字索引(在這種情況下很簡單),則可以對基本numpy數據使用索引:

df.values[arange(5),[0,0,1,2,1]]

out: array([ 1,  4,  8, 12, 14])

這將比列表推導或其他顯式迭代更加有效。

您始終可以使用列表推導:

[df.loc[idx, col] for idx, col in enumerate(['a', 'a', 'b', 'c', 'b'])]

正如 MorningGlory 在評論中所說, lookup已在1.2.0版本中被棄用。

文檔指出,使用meltloc可以實現相同的目的,但我認為這不是很明顯,所以就這樣了。

首先,使用melt創建查找DataFrame

i = pd.Series(["a", "a", "b", "c", "b"], name="col")
melted = pd.melt(
    pd.concat([i, df], axis=1),
    id_vars="col",
    value_vars=df.columns,
    ignore_index=False,
)

  col variable  value
0   a        a      1
1   a        a      4
2   b        a      7
3   c        a     10
4   b        a     13
0   a        b      2
1   a        b      5
2   b        b      8
3   c        b     11
4   b        b     14
0   a        c      3
1   a        c      6
2   b        c      9
3   c        c     12
4   b        c     15

然后,使用loc僅獲取相關值:

result = melted.loc[melted["col"] == melted["variable"], "value"]

0     1
1     4
2     8
4    14
3    12
Name: value, dtype: int64

最后 - 如果需要 - 獲得與以前相同的索引順序:

result.loc[df.index]

0     1
1     4
2     8
3    12
4    14
Name: value, dtype: int64

Pandas 還在文檔中使用factorizenumpy索引提供了不同的解決方案:

df = pd.concat([i, df], axis=1)
idx, cols = pd.factorize(df['col'])
df.reindex(cols, axis=1).to_numpy()[np.arange(len(df)), idx]

[ 1  4  8 12 14]

暫無
暫無

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

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