[英]Pandas dataframe get first row of each group
我有一個熊貓DataFrame
,如下所示:
df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4,5,6,6,6,7,7],
'value' : ["first","second","second","first",
"second","first","third","fourth",
"fifth","second","fifth","first",
"first","second","third","fourth","fifth"]})
我想按["id","value"]
對它進行分組並獲取每個組的第一行:
id value
0 1 first
1 1 second
2 1 second
3 2 first
4 2 second
5 3 first
6 3 third
7 3 fourth
8 3 fifth
9 4 second
10 4 fifth
11 5 first
12 6 first
13 6 second
14 6 third
15 7 fourth
16 7 fifth
預期結果:
id value
1 first
2 first
3 first
4 second
5 first
6 first
7 fourth
我嘗試了以下操作,它只給出了DataFrame
的第一行。 對此的任何幫助表示贊賞。
In [25]: for index, row in df.iterrows():
....: df2 = pd.DataFrame(df.groupby(['id','value']).reset_index().ix[0])
>>> df.groupby('id').first()
value
id
1 first
2 first
3 first
4 second
5 first
6 first
7 fourth
如果您需要id
作為列:
>>> df.groupby('id').first().reset_index()
id value
0 1 first
1 2 first
2 3 first
3 4 second
4 5 first
5 6 first
6 7 fourth
要獲取 n 個第一條記錄,您可以使用 head():
>>> df.groupby('id').head(2).reset_index(drop=True)
id value
0 1 first
1 1 second
2 2 first
3 2 second
4 3 first
5 3 third
6 4 second
7 4 fifth
8 5 first
9 6 first
10 6 second
11 7 fourth
12 7 fifth
這將為您提供每組的第二行(零索引,nth(0) 與 first() 相同):
df.groupby('id').nth(1)
文檔:http: //pandas.pydata.org/pandas-docs/stable/groupby.html#taking-the-nth-row-of-each-group
如果您需要獲得第一行,我建議使用.nth(0)
而不是 .first( .first()
。
它們之間的區別在於它們如何處理 NaN,因此.nth(0)
將返回 group 的第一行,無論該行中的值是什么,而.first()
最終將返回每列中的第一個非NaN
值。
例如,如果您的數據集是:
df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4],
'value' : ["first","second","third", np.NaN,
"second","first","second","third",
"fourth","first","second"]})
>>> df.groupby('id').nth(0)
value
id
1 first
2 NaN
3 first
4 first
和
>>> df.groupby('id').first()
value
id
1 first
2 second
3 first
4 first
如果您只需要每個組中的第一行,我們可以使用drop_duplicates
,注意函數默認方法keep='first'
。
df.drop_duplicates('id')
Out[1027]:
id value
0 1 first
3 2 first
5 3 first
9 4 second
11 5 first
12 6 first
15 7 fourth
也許這就是你想要的
import pandas as pd
idx = pd.MultiIndex.from_product([['state1','state2'], ['county1','county2','county3','county4']])
df = pd.DataFrame({'pop': [12,15,65,42,78,67,55,31]}, index=idx)
pop state1 county1 12 county2 15 county3 65 county4 42 state2 county1 78 county2 67 county3 55 county4 31
df.groupby(level=0, group_keys=False).apply(lambda x: x.sort_values('pop', ascending=False)).groupby(level=0).head(3)
> Out[29]:
pop
state1 county3 65
county4 42
county2 15
state2 county1 78
county2 67
county3 55
我想“第一”意味着您已經根據需要對 DataFrame 進行了排序。
我要做的是:
df.groupby('id').agg('first') 我想“first”意味着您已經根據需要對 DataFrame 進行了排序。 我要做的是:
df.groupby('id').agg('first')
value
id
1 first
2 first
3 first
4 second
5 first
6 first
7 fourth
好的是你可以插入任何你想要的功能:
df.groupby('id').agg(['first','last','count']))
value
first last count
id
1 first second 3
2 first second 2
3 first fifth 4
4 second fifth 2
5 first first 1
6 first third 3
7 fourth fifth 2
輸出 DataFrame 具有 MultiIndex 列
MultiIndex([('value', 'first'),
('value', 'last'),
('value', 'count')],
)
考慮到'id'
列是數字類型,例如int32
/ int64
,也可以使用groupby.rank()
如下
[In]: df[df.groupby('value')['id'].rank() == 1]
[Out]:
id value
0 1 first
6 3 third
7 3 fourth
8 3 fifth
如果要重置索引,只需傳遞.reset_index()
例如
[In]: df[df.groupby('value')['id'].rank() == 1].reset_index()
[Out]:
index id value
0 0 1 first
1 6 3 third
2 7 3 fourth
3 8 3 fifth
如果不需要index
和id
列
[In]: df.drop(['index', 'id'], axis=1, inplace=True)
[Out]:
value
0 first
1 third
2 fourth
3 fifth
您可以使用接受要選擇的元素索引列表的方法take
:
df.groupby('id').take([0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.