-
[x] I have checked that this issue has not already been reported.
-
[x] I have confirmed this bug exists on the latest version of pandas.
-
[x] (optional) I have confirmed this bug exists on the master branch of pandas.
Code Sample, a copy-pastable example
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'group_col': [0.0, np.nan, 0.0, 0.0], 'value_col': [2,2,2,2]})
df2 = pd.DataFrame({'group_col': [np.nan, 0.0, 0.0, 0.0], 'value_col': [2,2,2,2]})
groupby apply on df1
gives multi-index output
df1.groupby('group_col').value_col.apply(lambda x: x.value_counts().reindex(index=[1,2,3]))
group_col
0.0 1 NaN
2 3.0
3 NaN
Name: value_col, dtype: float64
groupby apply on df2
gives a single level index output:
df2.groupby('group_col').value_col.apply(lambda x: x.value_counts().reindex(index=[1,2,3]))
0 NaN
1 NaN
2 3.0
3 NaN
Name: value_col, dtype: float64
Problem description
groupby apply on df1
and df2
produce different outputs. They should produce the same output.
Expected Output
The output of both the above mentioned examples should be this:
group_col
0.0 1 NaN
2 3.0
3 NaN
Name: value_col, dtype: float64
Output of pd.show_versions()
Comment From: jendrikjoe
Not sure, if it is the exact same issue, but we see a similar inconsistency when doing conditional filtering. A minimal reproducible example:
df = pd.DataFrame(
index=["a", "b", "c", "d"],
data=[(0, 1.), (0, 2.), (1, 3.), (1, 4.)],
columns=["group_col", "value"]
)
Doing an apply with a value that actually triggers filtering (<3
):
df.groupby("group_col").apply(
lambda df: df[["value"]] if all(df["value"] < 3) else df.iloc[1:][["value"]]
)
>>> value
group_col
0 a 1.0
b 2.0
1 d 4.0
Doing an apply with a value that does not trigger filtering (<5
):
```python df.groupby("group_col").apply( lambda df: df[["value"]] if all(df["value"] < 5) else df.iloc[1:][["value"]] )
value a 1.0 b 2.0 c 3.0 d 4.0
Expected output:
I would expect the latter to output:
```python
value
group_col
0 a 1.0
b 2.0
1 c 3.0
d 4.0
Output of pd.show_versions()
INSTALLED VERSIONS ------------------ commit : None python : 3.8.2.final.0 python-bits : 64 OS : Darwin OS-release : 19.4.0 machine : x86_64 processor : i386 byteorder : little LC_ALL : en_US.UTF-8 LANG : en_US.UTF-8 LOCALE : en_US.UTF-8 pandas : 1.0.3 numpy : 1.18.4 pytz : 2020.1 dateutil : 2.8.1 pip : 20.0.2 setuptools : 46.1.3 Cython : None pytest : None hypothesis : None sphinx : None blosc : None feather : None xlsxwriter : None lxml.etree : None html5lib : None pymysql : None psycopg2 : None jinja2 : 2.11.2 IPython : 7.14.0 pandas_datareader: None bs4 : None bottleneck : None fastparquet : 0.4.0 gcsfs : None lxml.etree : None matplotlib : 3.2.1 numexpr : None odfpy : None openpyxl : None pandas_gbq : None pyarrow : None pytables : None pytest : None pyxlsb : None s3fs : None scipy : 1.4.1 sqlalchemy : None tables : None tabulate : None xarray : None xlrd : None xlwt : None xlsxwriter : None numba : 0.49.1Comment From: gurukiran07
@jendrikjoe Might be related. Not sure.
Example:
df2.groupby('group_col').value_col.apply(lambda x: x.value_counts().reindex(index=[1,2,3]))
0 NaN
1 NaN
2 3.0
3 NaN
Name: value_col, dtype: float64
df2.head(3).groupby('group_col').value_col.apply(lambda x: x.value_counts().reindex(index=[1,2,3]))
group_col
0.0 1 NaN
2 2.0
3 NaN
Name: value_col, dtype: float64
**Comment From: gimseng**
I played around with a little bit more with df1 and df2. If I changed the index list in the reindex argument, I get (the right multilevel answer):
```Python
df2.groupby('group_col').value_col.apply(lambda x: x.value_counts().reindex(index=[1,2]))
group_col
0.0 1 NaN
2 3.0
Name: value_col, dtype: float64
As another example, I shortened the data and try with different index list. Here are the few outputs:
df3 = pd.DataFrame({'group_col': [np.nan, 0.0,0.0], 'value_col': [2,2,2]})
df3.groupby('group_col').value_col.apply(lambda x: x.value_counts().reindex(index=[1,2]))
0 NaN
1 NaN
2 2.0
Name: value_col, dtype: float64
and
df4 = pd.DataFrame({'group_col': [np.nan, 0.0], 'value_col': [2,2]})
df4.groupby('group_col').value_col.apply(lambda x: x.value_counts().reindex(index=[1]))
0 NaN
1 NaN
Name: value_col, dtype: float64
I suspect there is something about (re)-indexing and missing value. I would love to work on this, but I am new to this repo. If someone else could point me towards the right direction, I'd be happy to investigate further.
Output of pd.show_versions()
Details
INSTALLED VERSIONS ------------------ commit : None python : 3.6.9.final.0 python-bits : 64 OS : Linux OS-release : 4.19.104+ machine : x86_64 processor : x86_64 byteorder : little LC_ALL : None LANG : en_US.UTF-8 LOCALE : en_US.UTF-8 pandas : 1.0.4 numpy : 1.18.4 pytz : 2018.9 dateutil : 2.8.1 pip : 19.3.1 setuptools : 47.1.1 Cython : 0.29.19 pytest : 3.6.4 hypothesis : None sphinx : 1.8.5 blosc : None feather : 0.4.1 xlsxwriter : None lxml.etree : 4.2.6 html5lib : 1.0.1 pymysql : None psycopg2 : 2.7.6.1 (dt dec pq3 ext lo64) jinja2 : 2.11.2 IPython : 5.5.0 pandas_datareader: 0.8.1 bs4 : 4.6.3 bottleneck : 1.3.2 fastparquet : None gcsfs : None lxml.etree : 4.2.6 matplotlib : 3.2.1 numexpr : 2.7.1 odfpy : None openpyxl : 2.5.9 pandas_gbq : 0.11.0 pyarrow : 0.14.1 pytables : None pytest : 3.6.4 pyxlsb : None s3fs : 0.4.2 scipy : 1.4.1 sqlalchemy : 1.3.17 tables : 3.4.4 tabulate : 0.8.7 xarray : 0.15.1 xlrd : 1.1.0 xlwt : 1.3.0 xlsxwriter : None numba : 0.48.0Comment From: rhshadrach
I now get the expected output in the OP.
Comment From: parthi-siva
take