eymentakak
eymentakak

Reputation: 140

pandas groupby after nan value

I want to collect the rows found after the nan value in var1 up to another nan value under the var2 category of the nan value. how can I do that ?

the attached table is just the head(20)

        var1         var2   
    
    2   NaN         ADIYAMAN ÜNİVERSİTESİ (Devlet Üniversitesi) 
    3   NaN         Besni Ali Erdemoğlu Meslek Yüksekokulu  
    4   100290102   Bankacılık ve Sigortacılık  
    5   100290109   Bilgi Yönetimi  
    6   100290116   Bilgisayar Programcılığı    
    7   100290123   Büro Yönetimi ve Yönetici Asistanlığı   
    8   100290130   İşletme Yönetimi    
    9   100290137   Mekatronik  
    10  100290144   Muhasebe ve Vergi Uygulamaları  
    11  NaN         Gölbaşı Meslek Yüksekokulu  
    12  100290070   Bankacılık ve Sigortacılık  
    13  100250476   Bilgisayar Programcılığı    
    14  100250591   Büro Yönetimi ve Yönetici Asistanlığı   
    15  100290056   İş Sağlığı ve Güvenliği 
    16  100250767   Lojistik    
    17  100250555   Yerel Yönetimler    
    18  NaN         Kahta Meslek Yüksekokulu    
    19  100250713   Bahçe Tarımı    
    20  100250652   Bankacılık ve Sigortacılık  
    21  100250485   Bilgisayar Programcılığı    

.

df["var1"].isnull().sum
var1         1185

Upvotes: 1

Views: 179

Answers (3)

Bill
Bill

Reputation: 11603

Is this what you wanted?

# Make a toy dataset with nans in it
df = pd.DataFrame(np.arange(1, 25).reshape((12, 2)), columns=['A', 'B'])
for _ in range(3):
    df.iloc[np.random.randint(12), 0] = np.nan
print(df)

# break into segments based on nans in column 'A'
nan_rows = df['A'].isnull()
segment_starts = np.diff(np.concatenate([[1], nan_rows])) == -1
segment_ends = np.diff(np.concatenate([nan_rows, [1]])) == 1
segments = [
    df.iloc[start:end+1, :]
    for start, end in zip(np.nonzero(segment_starts)[0], 
                          np.nonzero(segment_ends)[0])
]
print(pd.concat(segments, keys=range(len(segments))))

Output:

       A   B
0    1.0   2
1    3.0   4
2    5.0   6
3    7.0   8
4    NaN  10
5   11.0  12
6   13.0  14
7    NaN  16
8    NaN  18
9   19.0  20
10  21.0  22
11  23.0  24
         A   B
0 0    1.0   2
  1    3.0   4
  2    5.0   6
  3    7.0   8
1 5   11.0  12
  6   13.0  14
2 9   19.0  20
  10  21.0  22
  11  23.0  24

Upvotes: 0

Baron Legendre
Baron Legendre

Reputation: 2188

df
###
   value1  value2
0     1.0     1.0
1     2.0     2.0
2     3.0     3.0
3     4.0     4.0
4     5.0     5.0
5     NaN     NaN
6     7.0     7.0
7     NaN     NaN
8     9.0     9.0
9     NaN    10.0
df.query('value1.isnull() & value2.isnull()')
###
   value1  value2
5     NaN     NaN
7     NaN     NaN

Upvotes: 1

Dina Kisselev
Dina Kisselev

Reputation: 86

Are you looking to select all var2 values where var1 is not Null? In that case, you'd need:

df[df['var1'].notnull()]['var2']

This will select all var2 values where var1 is not Null.

Upvotes: 1

Related Questions