I have some data from an experiment, and within each trial there are some single values, surrounded by NA
's, that I want to fill out to the entire trial:
df = pd.DataFrame({'trial': [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3],
'cs_name': [np.nan, 'A1', np.nan, np.nan, np.nan, np.nan, 'B2',
np.nan, 'A1', np.nan, np.nan, np.nan]})
Out[177]:
cs_name trial
0 NaN 1
1 A1 1
2 NaN 1
3 NaN 1
4 NaN 2
5 NaN 2
6 B2 2
7 NaN 2
8 A1 3
9 NaN 3
10 NaN 3
11 NaN 3
I'm able to fill these values within the whole trial by using both bfill()
and ffill()
, but I'm wondering if there is a better way to achieve this.
df['cs_name'] = df.groupby('trial')['cs_name'].ffill()
df['cs_name'] = df.groupby('trial')['cs_name'].bfill()
Expected output:
cs_name trial
0 A1 1
1 A1 1
2 A1 1
3 A1 1
4 B2 2
5 B2 2
6 B2 2
7 B2 2
8 A1 3
9 A1 3
10 A1 3
11 A1 3
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…