import pandas as pd
df = pd.DataFrame({'a': [1, 1, 1, 2], 'b': [11, 11, None, None]})
# a b
# 0 1 11.0
# 1 1 11.0
# 2 1 NaN
# 3 2 NaN
df.groupby('a').ffill()
# b
# 0 11.0
# 1 11.0
# 2 11.0
# 3 NaN
Filling missing values in groups removes the column upon which DataFrame got grouped by.
Previously (0.20.2) list of columns was left intact after such operation.
DataFrame containing the same list of columns as before the operation.
pd.show_versions()commit : None
python : 3.6.7.final.0
python-bits : 64
OS : Linux
OS-release : 4.15.0-55-generic
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8
pandas : 0.25.0
numpy : 1.16.4
pytz : 2019.1
dateutil : 2.8.0
pip : 19.2.1
setuptools : 40.6.3
Cython : 0.27.3
pytest : 3.0.7
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.2.6
html5lib : None
pymysql : None
psycopg2 : 2.7.3.2 (dt dec pq3 ext lo64)
jinja2 : 2.10
IPython : 7.2.0
pandas_datareader: None
bs4 : 4.6.3
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : 4.2.6
matplotlib : 2.0.2
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : 0.13.0
pytables : None
s3fs : None
scipy : 1.0.0
sqlalchemy : 1.1.18
tables : None
xarray : None
xlrd : None
xlwt : None
xlsxwriter : None
see the whatsnew https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.25.0.html#dataframe-groupby-ffill-bfill-no-longer-return-group-labels
this was a regression
@jreback the behavior is not consistent at all. For .sum() grouped column values are moved to the index series while .ffill() just gets rid of them.
Proof:
df = pd.DataFrame({'a': ['a','b','c'], 'v':[1,2,3]})
df.groupby('a').sum()
Out[21]:
v
a
a 1
b 2
c 3
df.groupby('a').ffill()
Out[22]:
v
0 1
1 2
2 3
https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#aggregation
sum is an aggregation while filling is a transformation
@jreback: Is the note at the end of the transformation section no longer valid?
https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#transformation
Note
Some functions will automatically transform the input when applied to a GroupBy object, but returning an object of the same shape as the original. Passing as_index=False will not affect these transformation methods.
For example: fillna, ffill, bfill, shift..
Is there a chained/functional syntax to fill missing values? Is
df.update(df.sort_values(['key1', 'time']).groupby('key1').ffill()) the only option to get a dataframe with the na's filled in?
Most helpful comment
@jreback the behavior is not consistent at all. For
.sum()grouped column values are moved to the index series while.ffill()just gets rid of them.Proof: