DataFrame的apply()、applymap()、map()方法

       对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

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

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

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)

4 Groupby方法

df.groupby('class').mean()

df.groupby('petalwidth')['class'].unique().to_frame()

df.groupby('petalwidth')['class'].unique().to_frame()

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如下:

applymap() 作用于每一个元素

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

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

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

tips.head()

Out[34]:

total_billtipsmokerdaytimesizetip_pct
016.991.01NoSunDinner20.059447
110.341.66NoSunDinner30.160542
221.013.50NoSunDinner30.166587
323.683.31NoSunDinner20.139780
424.593.61NoSunDinner40.146808

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

tips.groupby('smoker').apply(top)

Out[38]:

total_billtipsmokerdaytimesizetip_pct
smoker
No8824.715.85NoThurLunch20.236746
18520.695.00NoSunDinner50.241663
5110.292.60NoSunDinner20.252672
1497.512.00NoThurLunch20.266312
23211.613.39NoSatDinner20.291990
Yes10914.314.00YesSatDinner20.279525
18323.176.50YesSunDinner40.280535
673.071.00YesSatDinner10.325733
1789.604.00YesSunDinner20.416667
1727.255.15YesSunDinner20.710345

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

且行且安~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值