当前位置: 代码迷 >> python >> 如何基于熊猫groupby对象中的组大小建立if条件
  详细解决方案

如何基于熊猫groupby对象中的组大小建立if条件

热度:71   发布时间:2023-06-14 08:49:48.0

这个问题可能很简单,但是我不知道该怎么做。 我有按列分组的数据框。 我想绘制每个组,但前提是其大小> 2。

Here is my code:
df1=df.groupby('Origin')

import matplotlib.pyplot as plt

for key, group in df1:
        plt.figure()
        group.plot(x='xColumnr', y='yColumn', title=str(key))

我试图使用df2=df1.filter(lambda group: group.size() > 2)过滤掉这些组,并在我的代码中将df2设置为df1,但这给了我错误TypeError: 'numpy.int32' object is not callable 然后我尝试

df3=df1.size()
if df3[df3 > 2]:
    plot stuff

引发异常“ True和False列丢失”。 如何在if条件下构建以仅绘制大小大于2的组?

您应该能够遍历数据集并确定组是否具有足够的数据:

import pandas as pd

import matplotlib.pyplot as plt

names = ['Bob','Jessica','Mary','John','Mel']
zipcode = [100, 100, 77, 77, 973]
weight = [100, 200, 300, 400, 500]

BabyDataSet = zip(names,zipcode, weight)

df = pd.DataFrame(data = BabyDataSet, columns=['Name', 'Zipcode', 'Weight'])

grouped = df.groupby(df.Zipcode)

for key, group in grouped:
    entries = group.size
    columns = len(group.columns)
    if entries/columns >= 2:
        plt.figure()
        group.plot(x='Zipcode', y='Weight', title=str(key))

不过,也许还有更好的方法。

受启发的示例