Keep columns after a groupby in an empty dataframe

廉价感情. 提交于 2019-12-23 10:07:13

问题


The dataframe is an empty df after query.when groupby,raise runtime waring,then get another empty dataframe with no columns.How to keep the columns?

df = pd.DataFrame(columns=["PlatformCategory","Platform","ResClassName","Amount"])
print df

result:

Empty DataFrame
Columns: [PlatformCategory, Platform, ResClassName, Amount]
Index: []

then groupby:

df = df.groupby(["PlatformCategory","Platform","ResClassName"]).sum()
df = df.reset_index(drop=False,inplace=True)
print df

result: sometimes is None sometime is empty dataframe

Empty DataFrame
Columns: []
Index: []

why empty dataframe has no columns.

runtimewaring:

/data/pyrun/lib/python2.7/site-packages/pandas/core/groupby.py:3672: RuntimeWarning: divide by zero encountered in log

if alpha + beta * ngroups < count * np.log(count):

/data/pyrun/lib/python2.7/site-packages/pandas/core/groupby.py:3672: RuntimeWarning: invalid value encountered in double_scalars
  if alpha + beta * ngroups < count * np.log(count):

回答1:


You need as_index=False and group_keys=False:

df = df.groupby(["PlatformCategory","Platform","ResClassName"], as_index=False).count()
df

Empty DataFrame
Columns: [PlatformCategory, Platform, ResClassName, Amount]
Index: []

No need to reset your index afterwards.



来源:https://stackoverflow.com/questions/46090386/keep-columns-after-a-groupby-in-an-empty-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!