Zählen unter Bedingungen

mit matplotlib, NumPy, pandas, SciPy, SymPy und weiteren mathematischen Programmbibliotheken.
Antworten
st_baum
User
Beiträge: 26
Registriert: Sonntag 24. Mai 2020, 13:54

Ich möchte gerne, ähnlich wie ZÄHLWENN in Excel, Werte (0 oder 1) in einer Spalte zählen, sofern eine Bedingung in einer anderen Spalte erfüllt ist.

So sieht der Datensatz aus

Code: Alles auswählen

import pandas as pd
d = {'col1': [1, 2, 3, 3], 'col2': [0, 1, 0, 1]}
df2 = pd.DataFrame(data=d)
Ich hatte mir das wie folgt gedacht:

Code: Alles auswählen

df2['col2'].isin([0]).sum()(df2['col1']  <  3)
Klappt leider nicht. Hat jemand eine Lösung?
Benutzeravatar
__blackjack__
User
Beiträge: 13268
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@st_baum: Wie soll denn das gewünschte Ergebnis aussehen?
Please call it what it is: copyright infringement, not piracy. Piracy takes place in international waters, and involves one or more of theft, murder, rape and kidnapping. Making an unauthorized copy of a piece of software is not piracy, it is an infringement of a government-granted monopoly.
st_baum
User
Beiträge: 26
Registriert: Sonntag 24. Mai 2020, 13:54

Achso, das wäre natürlich hilfreich :-P

ich möchte zählen, wie oft der Wert Null in einer Spalte vorkommt. Gezählt werden soll nur, wenn in der anderen Spalte die genannte Bedingung erfüllt ist. Es reicht, wenn die resultierende Zahl in einer variable gespeichert wird.
Benutzeravatar
__blackjack__
User
Beiträge: 13268
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

Also eine Und-Verknüpfung von zwei Bedingungen und dann zählen.

Code: Alles auswählen

In [170]: df2["col1"] < 3                                                       
Out[170]: 
0     True
1     True
2    False
3    False
Name: col1, dtype: bool

In [171]: df2["col2"] == 0                                                      
Out[171]: 
0     True
1    False
2     True
3    False
Name: col2, dtype: bool

In [172]: (df2["col1"] < 3) & (df2["col2"] == 0)                                
Out[172]: 
0     True
1    False
2    False
3    False
dtype: bool

In [173]: ((df2["col1"] < 3) & (df2["col2"] == 0)).sum()                        
Out[173]: 1
Please call it what it is: copyright infringement, not piracy. Piracy takes place in international waters, and involves one or more of theft, murder, rape and kidnapping. Making an unauthorized copy of a piece of software is not piracy, it is an infringement of a government-granted monopoly.
st_baum
User
Beiträge: 26
Registriert: Sonntag 24. Mai 2020, 13:54

Prima, danke!
Antworten