Mam dataframe z 2 kolumnami:

          Col1          Col2
1          NaN         Someval1
2           Y          Someval2
3           N          Someval3
4          NaN           NaN
5          NaN         Someval4

Chciałbym wypełnić Nan warunkami:

If Col1 has NaN and Col2 has a Someval1 that is in list 1 then fillna with Y
If Col1 has NaN and Col2 has a Someval4 that is in list 2 then fillna with N
If Col1 has NaN and Col2 has a NaN that is in list 2 then fillna with N

Jakieś sugestie ? (Nie wiem, czy to możliwe)

Wielkie dzięki !

3
datascana 27 czerwiec 2017, 11:41

3 odpowiedzi

Najlepsza odpowiedź

Myślę, że potrzebujesz mask , na warunki isnull i {x2}}:

L1 = ['Someval1','Someval8']
L2 = ['Someval4','Someval9', np.nan]
m1 = df['Col1'].isnull()
m2 = df['Col2'].isin(L1)
m3 = df['Col2'].isin(L2)

df['Col1'] = df['Col1'].mask(m1 & m2, 'Y')
df['Col1'] = df['Col1'].mask(m1 & m3, 'N')

print (df)
  Col1      Col2
1    Y  Someval1
2    Y  Someval2
3    N  Someval3
4    N       NaN
5    N  Someval4

Kolejne rozwiązanie z numpy.where:

df['Col1'] = np.where(m1 & m2, 'Y',
             np.where(m1 & m3, 'N', df['Col1']))

print (df)
  Col1      Col2
1    Y  Someval1
2    Y  Someval2
3    N  Someval3
4    N       NaN
5    N  Someval4

Inne rozwiązanie z jednym warunkami i {x0}}:

L1 = ['Someval1','Someval8']
L2 = ['Someval4','Someval9', np.nan]

df['Col1'] = df['Col1'].mask(df['Col2'].isin(L1), df['Col1'].fillna('Y'))
df['Col1'] = df['Col1'].mask(df['Col2'].isin(L2), df['Col1'].fillna('N'))
print (df)
  Col1      Col2
1    Y  Someval1
2    Y  Someval2
3    N  Someval3
4    N       NaN
5    N  Someval4
4
jezrael 27 czerwiec 2017, 08:56

Oto {X0}}

df.loc[df.Col1.isnull() & df.Col2.isin(['Someval1']), 'Col1'] = 'Y'
df.loc[df.Col1.isnull() & df.Col2.isin(['Someval4']), 'Col1'] = 'N'
df.loc[df.Col1.isnull() & df.Col2.isin([np.nan]), :] = 'N'

Pełny skrypt:

df = pd.read_csv(StringIO("""Col1          Col2
1          NaN         Someval1
2           Y          Someval2
3           N          Someval3
4          NaN           NaN
5          NaN         Someval4
"""), sep="\s+")

df.loc[df.Col1.isnull() & df.Col2.isin(['Someval1']), 'Col1'] = 'Y'
df.loc[df.Col1.isnull() & df.Col2.isin(['Someval4']), 'Col1'] = 'N'
df.loc[df.Col1.isnull() & df.Col2.isin([np.nan]), :] = 'N'

df

  Col1      Col2
1    Y  Someval1
2    Y  Someval2
3    N  Someval3
4    N         N
5    N  Someval4
0
tworec 27 czerwiec 2017, 09:21

Możesz użyć

df.Col1[(df['Col1'].isnull())&(df['Col2']=='Someval1')] = 'Y'
df.Col1[(df['Col1'].isnull())&(df['Col2']=='Someval4')] = 'N'
df.Col1[(df['Col1'].isnull())&(df['Col2'].isnull())] = 'N'
0
danche 27 czerwiec 2017, 09:18