我试图创建一个函数来创建一个透视表,我需要基于字符串过滤一列。你知道吗
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”错误。在函数中进行通配符搜索有不同的方法吗?你知道吗
假设你想找出每个品种的年龄总和,在他们的度量中。你可以采取以下方法。你知道吗
现在让我们创建一个布尔函数来检查dataframe
df
的Metrics
列中的单词完成情况。你知道吗现在您可以对Breed和变量
bool
进行groupby
运算,以找到年龄的总和。你知道吗因为在样本数据中没有“completion”字,所以返回的都是false。但是我们可以检查“walked”这个词,因为有一些行中存在walked。你知道吗
希望,这就是你想做的。你知道吗
更新 根据评论:
相关问题 更多 >
编程相关推荐