devo dire che questo è strano modo per applicare una funzione a un df panda, in ogni caso questo è un esempio che mostra ciò che fa:
In [280]:
# create the df
df = pd.DataFrame({'a':np.arange(10), 'b':[1,1,1,2,2,3,3,4,5,5]})
df
Out[280]:
a b
0 0 1
1 1 1
2 2 1
3 3 2
4 4 2
5 5 3
6 6 3
7 7 4
8 8 5
9 9 5
l'espressione lambda sta chiamando apply
e passando axis=1
che significa row-wise e testare ogni colonna denominata per se l'espressione è vera o falsa, la (0,1)
getta l'accaduto a un int
, altrimenti si otterrebbe un dtype booleano restituito.
In [285]:
df.apply(lambda x: x['a'] > 5 and x['b'] < 5, axis=1)
Out[285]:
0 False
1 False
2 False
3 False
4 False
5 False
6 True
7 True
8 False
9 False
dtype: bool
Con il (0,1)
Cast:
In [282]:
# apply a lambda, test if 'a' is greater and 5 and 'b' is less than 5, row-wise, cast the result to 1, 0 if True or False
df.apply(lambda x: (0,1)[x['a'] > 5 and x['b'] < 5], axis=1)
Out[282]:
0 0
1 0
2 0
3 0
4 0
5 0
6 1
7 1
8 0
9 0
dtype: int64
il modo in cui i panda sarebbe quello di fare in questo modo:
In [284]:
((df['a'] > 5) & (df['b'] < 5)).astype(int)
Out[284]:
0 0
1 0
2 0
3 0
4 0
5 0
6 1
7 1
8 0
9 0
dtype: int32
Non so R, quindi non posso commentare in merito
Ragazzo che è un pezzo di codice illeggibile. –
@MartijnPieters Considerando che ha spinto il lettore del codice a postare una domanda chiedendo cosa fa, direi che hai ragione :) – CoryKramer
Non sai perché i downvotes, anche se un po 'più di contesto sarebbe utile. 'Df' a' dict' o numpy dataframe? – kdopen