DataFrame的apply()、applymap()、map()方法[通俗易懂]

DataFrame的apply()、applymap()、map()方法[通俗易懂]对DataFrame对象中的某些行或列,或者对DataFrame对象中的所有元素进行某种运算或操作,我们无需利用低效笨拙的循环,DataFrame给我们分别提供了相应的直接而简单的方法,apply()和applymap()。其中apply()方法是针对某些行或列进行操作的,而applymap()方法则是针对所有元素进行操作的。1map()方法Themapmethod…

大家好,又见面了,我是你们的朋友全栈君。

       对DataFrame对象中的某些行或列,或者对DataFrame对象中的所有元素进行某种运算或操作,我们无需利用低效笨拙的循环,DataFrame给我们分别提供了相应的直接而简单的方法,apply()和applymap()。其中apply()方法是针对某些行或列进行操作的,而applymap()方法则是针对所有元素进行操作的。

 1 map()方法

The map method works on series, so in our case, we will use it to transform a column of our DataFrame, which remember is just a pandas Series. Suppose that we decide that the class names are a bit long for our taste and we would like to code them using our special threeletter coding system. We’ll use the map method with a Python dictionary as the argument toaccomplish this. We’ll pass in a replacement for each of the unique iris types:

df[‘class’] = df[‘class’].map({‘Iris-setosa’: ‘SET’, ‘Iris-virginica’:’VIR’, ‘Iris-versicolor’: ‘VER’})
df

DataFrame的apply()、applymap()、map()方法[通俗易懂]

2 Apply()方法

The apply method allows us to work with both DataFrames and Series. We’ll start with an example that would work equally well with map, then we’ll move on to examples that would work only with apply.

Using the iris DataFrame, let’s make a new column based on the petal width. We previously saw that the mean for the petal width was 1.3. Let’s now create a new column in our DataFrame, wide petal, that contains binary values based on the value in the petal width column. If the petal width is equal to or wider than the median, we will code it with a 1, and if it is less than the median, we will code it 0. We’ll do this using the apply method on the petal width column:

df[‘wide petal’] = df[‘petal width’].apply(lambda v: 1 if v >= 1.3 else 0)
df

DataFrame的apply()、applymap()、map()方法[通俗易懂]

df[‘petal area’] = df.apply(lambda r: r[‘petal length’] * r[‘petal width’],axis=1)
df

DataFrame的apply()、applymap()、map()方法[通俗易懂]

3 Applymap()方法

We’ve looked at manipulating columns and explained how to work with rows, but suppose that you’d like to perform a function across all data cells in your DataFrame; this is where applymap is the right tool. Let’s take a look at an example:

df.applymap(lambda v: np.log(v) if isinstance(v, float) else v)

DataFrame的apply()、applymap()、map()方法[通俗易懂]

4 Groupby方法

df.groupby(‘class’).mean()

df.groupby(‘petalwidth’)[‘class’].unique().to_frame()

df.groupby(‘petalwidth’)[‘class’].unique().to_frame()

DataFrame的apply()、applymap()、map()方法[通俗易懂]

df.groupby(‘petal width’)[‘class’].unique().to_frame()

df.groupby(‘class’).describe()

df.groupby(‘class’)[‘petal width’].agg({‘delta’: lambda x: x.max() – x.min(), ‘max’: np.max, ‘min’: np.min})

   

简单来说,apply()方法 可以作用于DataFrame 还有Series, 作用于一行或者一列时,我们不妨可以采用,因为可以通过设置axis=0/1 来把握,demo如下:

DataFrame的apply()、applymap()、map()方法[通俗易懂]

applymap() 作用于每一个元素

DataFrame的apply()、applymap()、map()方法[通俗易懂]

map可以作用于Series每一个元素的

DataFrame的apply()、applymap()、map()方法[通俗易懂]

总的来说,map()、aply()、applymap()方法是一种对series、dataframe极其方便的应用与映射函数。

最后,非常重要的一点,这些映射函数,里面都是可以放入自定义函数的。

tips.head()

Out[34]:

total_bill tip smoker day time size tip_pct
0 16.99 1.01 No Sun Dinner 2 0.059447
1 10.34 1.66 No Sun Dinner 3 0.160542
2 21.01 3.50 No Sun Dinner 3 0.166587
3 23.68 3.31 No Sun Dinner 2 0.139780
4 24.59 3.61 No Sun Dinner 4 0.146808

def top(df,n=5,column=’tip_pct’):
    return df.sort_values(by=column)[-n:]

tips.groupby(‘smoker’).apply(top)

Out[38]:

total_bill tip smoker day time size tip_pct
smoker
No 88 24.71 5.85 No Thur Lunch 2 0.236746
185 20.69 5.00 No Sun Dinner 5 0.241663
51 10.29 2.60 No Sun Dinner 2 0.252672
149 7.51 2.00 No Thur Lunch 2 0.266312
232 11.61 3.39 No Sat Dinner 2 0.291990
Yes 109 14.31 4.00 Yes Sat Dinner 2 0.279525
183 23.17 6.50 Yes Sun Dinner 4 0.280535
67 3.07 1.00 Yes Sat Dinner 1 0.325733
178 9.60 4.00 Yes Sun Dinner 2 0.416667
172 7.25 5.15 Yes Sun Dinner 2 0.710345
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/145590.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • java缓存数据并配置有效时间[通俗易懂]

    java缓存数据并配置有效时间[通俗易懂]没有用到redis只是单纯的使用内存存储数据实现的功能:缓存数据并配置有效时间,可设置默认时间自动清除缓存,也可以自己设置。直接上代码:importjava.util.LinkedList;importjava.util.List;importjava.util.Map.Entry;importjava.util.Timer;importjava.util.TimerTask;importjava.util.concurrent.ConcurrentHashMap;publ

    2022年10月4日
    0
  • oracle dmp导入导出_oracle导出数据

    oracle dmp导入导出_oracle导出数据Oracle数据导入导出imp/exp就相当于oracle数据还原与备份。exp命令可以把数据从远程数据库服务器导出到本地的dmp文件,imp命令可以把dmp文件从本地导入到远处的数据库服务器中。利用这个功能可以构建两个相同的数据库,一个用来测试,一个用来正式使用……Oracle数据导入导出imp/exp就相当于oracle数据还原与备份。exp命令可以把数据从远程数据库服务器导出到本地的dmp…

    2022年10月29日
    0
  • PHP headers_sent() 函数

    PHP headers_sent() 函数

    2021年9月20日
    37
  • django 聚合函数_sql聚合函数的用法

    django 聚合函数_sql聚合函数的用法前言orm模型中的聚合函数跟MySQL中的聚合函数作用是一致的,也有像Sum、Avg、Count、Max、Min,接下来我们逐个介绍聚合函数所有的聚合函数都是放在django.db.models

    2022年7月31日
    4
  • RPN网络讲解

    RPN网络讲解讲完了anchor机制,接下来我们讲RPN(regionproposalnetwork)区域候选网络。_build_network:https://github.com/endernewton/tf-faster-rcnn/blob/master/lib/nets/network.py原理解释FeatureMap进入RPN后,先经过一次33的卷积,同样,特征图大小依然是6040,数量…

    2022年6月23日
    40
  • python-回文字符串[通俗易懂]

    python-回文字符串[通俗易懂]回文字符串(10分)题目内容:给定一个字符串,判断它是否是回文字符串(即类似于peep,12321这样的对称字符串),如果是输出True,不是则输出False。判断过程中假定只考虑字母和数字字符,而且忽略字母的大小写和其它符号(如空格、标点符号等)。 输入格式:共一行,为一个字符串。 输出格式:共一行,为True或False。 输入样例: lo…

    2022年6月2日
    51

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号