I have data that resembles the following simplified example:
Col1 Col2 Col3
a A 10.1
b A NaN
d B NaN
e B 12.3
f B NaN
g C 14.1
h C NaN
i C NaN
...for many thousands of rows. I need to fillna based upon the value in Col2, using something analogous to the ffill method. The result I'm looking for is this:
Col1 Col2 Col3
a A 10.1
b A 10.1
d B NaN
e B 12.3
f B 12.3
g C 14.1
h C 14.1
i C 14.1
However, this method ignores the value in Col2. Any ideas?
If I understand correctly then you can groupby on 'Col2' and then call transform on 'Col3' and call ffill
:
In [35]:
df['Col3'] = df.groupby('Col2')['Col3'].transform(lambda x: x.ffill())
df
Out[35]:
Col1 Col2 Col3
0 a A 10.1
1 b A 10.1
2 d B NaN
3 e B 12.3
4 f B 12.3
5 g C 14.1
6 h C 14.1
7 i C 14.1
One answer I found is the following:
df['col3'] = df.groupby('Col2').transform('fillna',method='ffill')['col3']
Any thoughts?
Is this what you're looking for?
import pandas as pd
import numpy as np
df['Col3'] = np.where(df['Col2'] == 'A', df['Col3'].fillna(10.1), df["Col3"])
Of course replace accordingly.
You can take slices of the DataFrame for each element of Col2
, and then concatenate the results.
>>> pd.concat((df.loc[df.Col2 == letter, :].ffill() for letter in df.Col2.unique()))
Col1 Col2 Col3
0 a A 10.1
1 b A 10.1
2 d B NaN
3 e B 12.3
4 f B 12.3
5 g C 14.1
6 h C 14.1
7 i C 14.1
EDIT: It appears the method presented by @EdChum is the fastest by far.
%timeit pd.concat((df.loc[df.Col2 == letter, :].ffill() for letter in df.Col2.unique()))
100 loops, best of 3: 3.57 ms per loop
%timeit df.groupby('Col2').transform('fillna',method='ffill')['Col3']
100 loops, best of 3: 4.59 ms per loop
%timeit df.groupby('Col2')['Col3'].transform(lambda x: x.ffill())
1000 loops, best of 3: 746 µs per loop
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.