Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 由于值不足,从DataFrame中删除数据_Python_Python 3.x_Pandas - Fatal编程技术网

Python 由于值不足,从DataFrame中删除数据

Python 由于值不足,从DataFrame中删除数据,python,python-3.x,pandas,Python,Python 3.x,Pandas,我试着用下面的代码计算每月的总金额 month_sum = df.groupby(([df['Year'], df['Month']]))['amount'].agg(np.sum) 但是,如果这些数据没有包含足够的天数数据(例如:1月份只有10组数据),我需要删除这些数据或将总和结果更改为NaN 我只知道我可以通过dp.drop()删除数据,它根据列删除数据 特征…我不能在这种情况下使用它。有人能告诉我怎么做吗?您可以随时创建自定义聚合函数。 例如: 作为pd进口熊猫 df = pd.Dat

我试着用下面的代码计算每月的总金额

month_sum = df.groupby(([df['Year'], df['Month']]))['amount'].agg(np.sum)
但是,如果这些数据没有包含足够的天数数据(例如:1月份只有10组数据),我需要删除这些数据或将总和结果更改为NaN

我只知道我可以通过dp.drop()删除数据,它根据列删除数据
特征…我不能在这种情况下使用它。有人能告诉我怎么做吗?

您可以随时创建自定义聚合函数。
例如:

作为pd进口熊猫

df = pd.DataFrame(index=pd.date_range('2017-01-01', '2017-02-05'))
df['amount'] = range(len(df))


def custom_sum(s):
    if len(s) > 10:
        return s.sum()
    else:
        return None

g = df.groupby([df.index.year, df.index.month])['amount'].agg(custom_sum)
print(g)
输出:

2017  1    465.0
      2      NaN

考虑这个示例

df = pd.DataFrame({'year': ['2017']*20, 'month': list('1')*12 + list('2')*8, 'amount': np.random.randint(0,50,20)})
可以使用lambda按条件求和

df.groupby(['year', 'month']).amount.apply(lambda x: x.sum() if x.count() > 10 else np.nan).reset_index()
你得到

    year    month   amount
0   2017    1       249.0
1   2017    2       NaN
编辑:


借用@vaishali的数据集:

In [24]: df.groupby(['year', 'month']).amount \
           .agg(lambda x: x.sum() * 1 if x.count() > 10 else np.nan)
Out[24]:
year  month
2017  1        216.0
      2          NaN
Name: amount, dtype: float64

若要使用依赖于其他列的和的条件,该怎么办?df=(原始数据.groupby(['Year','Month'])['amount'].apply(如果原始数据['othercolumn'].sum()>=n else np.nan,则lambda x:x.sum())。重置_index())如果othercolumn sumIn [24]: df.groupby(['year', 'month']).amount \ .agg(lambda x: x.sum() * 1 if x.count() > 10 else np.nan) Out[24]: year month 2017 1 216.0 2 NaN Name: amount, dtype: float64