簡體   English   中英

如何按分組索引訪問 pandas groupby dataframe?

[英]How do I access a pandas groupby dataframe by grouped index?

按照這個例子,我可以創建一個簡單的 dataframe 和 groupby

import pandas as pd

# Create a sample data frame
df = pd.DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar'],
                   'B': range(5), 'C': range(5)})

# group by 'A' and sum 'B'
gf = df.groupby('A').agg({'B': 'sum'})

結果是分組的 dataframe gf

    B
A   
bar 7
foo 3

我想通過分組索引訪問 gf。 就像是...

gf['foo'] returns 3 
gf['bar'] returns 7

我還想按分組索引 plot。 就像是...

gf.plot('A', 'B') such that  x=['foo','bar'], y=[3,7]
gf.reset_index(level=0, inplace=True)

gf[gf.A == 'bar']

收益:

     A  B
0  bar  7

情節:

import matplotlib.pyplot as plt

plt.bar(gf.A, gf.B)

關於什么:

import matplotlib.pyplot as plt

for k in gf['B'].index:
    print "{}: {}".format(k, gf['B'].loc[k])

plt.bar(gf['B'].index, map(lambda i: gf['B'].loc[i], gf['B'].index))
plt.show()

在撰寫本文時,有一種方法可以在不使用 reset_index 的情況下訪問分組索引,該方法即將被棄用。 這是一個非常糟糕的過程,不應該使用,但是這里是:

df_counts.index.to_series().str[0]

返回

A
bar    b
foo    f
Name: A, dtype: object

這將為您提供與重置數據框並按該列編制索引一樣的信息。 具體來說, str索引之后的索引通過索引列表,比如['a', 'b']

要為 a 的這個值訪問 b 中的值,您可以:

gf[gf.index.to_series().str[0] == 'b']['B']

A
bar    7
Name: B, dtype: int64

並強制轉換為 int,如果您確定它是唯一的:

int(gf[gf.index.to_series().str[0] == 'b']['B'])

7

請記住,正如我發現的那樣,這是執行此查詢的一種糟糕方法,並且您應該非常喜歡 go 和@LN_P 的答案,它只是重置毫無意義地創建的索引,允許您正常訪問該列。

暫無
暫無

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

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