在学习python数据分析中,遇到了apply(lambda x:)这样的用法,原始代码如下
data_latest['Country'].apply(lambda x:data_latest['Country'].value_counts()[x])>1)
尝试理解这个用法,随机生成了一个数据如下,应该是取出来后两行数据,但是报错了,
正好前两行是重复的值,加上.value_counts(),然后>1,这样更改为取出重复大于1的,就不报错了
原因是什么呢?最下面是报错信息,不是很能看懂
df = pd.DataFrame(data=np.random.randint(0,100,size=(5,4)),columns=['a','b','c','d'])
a b c d
0 3 66 74 77
1 3 2 85 88
2 89 18 47 77
3 72 63 81 48
4 20 96 23 79
df['a'].apply(lambda x:df['a'][x]>10) #取出来大于10的值,应该是后两行
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
92-72e9d10c3921> in
----> 1 df['a'].apply(lambda x:df['a'][x]>1)
/opt/conda/lib/python3.6/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
3589 else:
3590 values = self.astype(object).values
-> 3591 mapped = lib.map_infer(values, f, convert=convert_dtype)
3592
3593 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()
92-72e9d10c3921> in (x)
----> 1 df['a'].apply(lambda x:df['a'][x]>1)
/opt/conda/lib/python3.6/site-packages/pandas/core/series.py in __getitem__(self, key)
866 key = com.apply_if_callable(key, self)
867 try:
--> 868 result = self.index.get_value(self, key)
869
870 if not is_scalar(result):
/opt/conda/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
4373 try:
4374 return self._engine.get_value(s, k,
-> 4375 tz=getattr(series.dtype, 'tz', None))
4376 except KeyError as e1:
4377 if len(self) > 0 and (self.holds_integer() or self.is_boolean()):
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
KeyError: 89
在这段代码中,apply() 方法是用来在数据框的某一列上应用函数的。
关于 lambda,它是 Python 中的匿名函数。匿名函数是指不用明确地定义函数名的函数,可以使用 lambda 关键字快速定义匿名函数。
在这里,lambda x: 定义了一个匿名函数,它的输入参数是 x。匿名函数的主体部分是 data_latest['Country'].value_counts()[x],它返回的是数据框 data_latest 中名为 'Country' 的列的频数。
最后,apply() 方法会在数据框中名为 'Country' 的列上应用这个匿名函数。
希望这对您有所帮助。如果您有其它问题,请随时联系我。