函数中的Use.filter

2024-10-03 21:24:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数来创建一个透视表,我需要基于字符串过滤一列。你知道吗

df = DataFrame({'Breed': ['Sheltie', 'Bernard', 'Husky', 'Husky', 'pig', 'Sheltie','Bernard'], 
            'Metric': ['One month walked', 'two month walked', 'three month walked', 'four month walked', 'one month waiting', 'two month waiting', 'Three month waiting'],
            'Age': [1,2,3,4,5,6,7]})

我想要一个数据透视表,其中汇总了所有狗的年龄,其中它们有一个“已完成”的指标,不管是哪个月。你知道吗

它看起来有点像这样:

                             Age
Breed      Metric            sum
------------------------------------
Husky  one month walked       4
Husky  four month walked      5

该函数将过滤掉任何不是“walk”的度量,同时汇总每个“completed”度量。你知道吗

我已经试过了。你知道吗

import pandas as pd
import fnmatch

def Dog_Walked_Completed(dfprime):
    return dfprime[dfprime['Breed'] == 'Husky'].groupby(['Breed','Metric']).fnmatch.filter(lambda df : (df['Metric']=='?completion')).any().agg({'Age': ['sum']})

但每当我尝试这样做时,就会得到一个“DataFrameGroupBy”对象没有属性“fnmatch”错误。在函数中进行通配符搜索有不同的方法吗?你知道吗


Tags: 函数dfagemetricbernardfourwaitingtwo
1条回答
网友
1楼 · 发布于 2024-10-03 21:24:52

假设你想找出每个品种的年龄总和,在他们的度量中。你可以采取以下方法。你知道吗

>>> import pandas as pd
>>> df = pd.DataFrame({'Breed': ['Sheltie', 'Bernard', 'Husky', 'Husky', 'pig', 'Sheltie','Bernard'],'Metric': ['One month walked', 'two month walked', 'three month walked', 'four month walked', 'one month waiting', 'two month waiting', 'Three month waiting'],'Age': [1,2,3,4,5,6,7]})
>>> df
   Age    Breed               Metric
0    1  Sheltie     One month walked
1    2  Bernard     two month walked
2    3    Husky   three month walked
3    4    Husky    four month walked
4    5      pig    one month waiting
5    6  Sheltie    two month waiting
6    7  Bernard  Three month waiting

现在让我们创建一个布尔函数来检查dataframe dfMetrics列中的单词完成情况。你知道吗

>>> bool = df['Metric'].str.contains('completion')

现在您可以对Breed和变量bool进行groupby运算,以找到年龄的总和。你知道吗

>>> pvt_tbl = df.groupby(['Breed',bool])['Age'].sum()
>>> pvt_tbl
Breed    Metric
Bernard  False     9
Husky    False     7
Sheltie  False     7
pig      False     5
Name: Age, dtype: int64

因为在样本数据中没有“completion”字,所以返回的都是false。但是我们可以检查“walked”这个词,因为有一些行中存在walked。你知道吗

>>> bool1 = df['Metric'].str.contains('walked')
>>> pvt_tbl1 = df.groupby(['Breed',bool1])['Age'].sum()
>>> pvt_tbl1
Breed    Metric
Bernard  False     7
         True      2
Husky    True      7
Sheltie  False     6
         True      1
pig      False     5
Name: Age, dtype: int64

希望,这就是你想做的。你知道吗

更新 根据评论:

>>> df.groupby(['Breed','Metric'])['Age'].sum()
Breed    Metric
Bernard  Three month waiting    7
         two month walked       2
Husky    four month walked      4
         three month walked     3
Sheltie  One month walked       1
         two month waiting      6
pig      one month waiting      5
Name: Age, dtype: int64

相关问题 更多 >