Groupby для выбора нескольких столбцов Pandas python - PullRequest
1 голос
/ 24 сентября 2019

У меня есть таблица данных df с 3 столбцами pandas, скажем:

[IN]:df
[OUT]:

Tree Name   Planted by Govt   Planted by College
A               Yes                No 
B               Yes                No
C               Yes                No 
C               Yes                No
A               No                 No 
B               No                 Yes
B               Yes                Yes
B               Yes                No
B               Yes                No  

Запрос:

Сколько деревьев было посажено правительством, а не колледжемдля каждого типа дерева.Правительство: Да, Пвт: Нет

Требуется вывод:

1 Tree(s) 'A' were planted by govt and not by college
3 Tree(s) 'B' were planted by govt and not by college
2 Tree(s) 'C' were planted by govt and not by college

Может кто-нибудь помочь, пожалуйста

Ответы [ 2 ]

1 голос
/ 24 сентября 2019

Или мы могли бы использовать количество

df[df['Planted by Govt'].eq('Yes')& df['Planted by College'].eq('No')].groupby('Tree Name').count()['Planted by Govt'].rename('PLanted only by Govt')

print(result)
Tree Name
A    1
B    3
C    2
Name: PLanted only by Govt, dtype: int64
1 голос
/ 24 сентября 2019

Сначала создайте логическую маску, сравнив оба столбца с & для побитового значения AND, а затем преобразуйте в числовое значение с совокупностью sum:

s = df['Planted by Govt'].eq('Yes') & df['Planted by College'].eq('No')
out = s.view('i1').groupby(df['Tree Name']).sum()
#alternative
#out = s.astype(int).groupby(df['Tree Name']).sum()
print (out)
Tree Name
A    1
B    3
C    2
dtype: int8

Последнее для пользовательского вывода: f-string s:

for k, v in out.items():
    print (f"{v} Tree(s) {k} were planted by govt and not by college")

    1 Tree(s) A were planted by govt and not by college
    3 Tree(s) B were planted by govt and not by college
    2 Tree(s) C were planted by govt and not by college

Другая идея - создать новый столбец для оригинала:

df['new'] = (df['Planted by Govt'].eq('Yes') & df['Planted by College'].eq('No')).view('i1')
print (df)
  Tree Name Planted by Govt Planted by College  new
0         A             Yes                 No    1
1         B             Yes                 No    1
2         C             Yes                 No    1
3         C             Yes                 No    1
4         A              No                 No    0
5         B              No                Yes    0
6         B             Yes                Yes    0
7         B             Yes                 No    1
8         B             Yes                 No    1

out = df.groupby('Tree Name')['new'].sum()
print (out)
Tree Name
A    1
B    3
C    2
Name: new, dtype: int8
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...