
本文是书《对比Excel,轻松学习Python数据分析》的第二篇,主要内容包含
Excel中区间切分使用的是if函数
=IF(A2<4,"<4",IF(A2<7,"4-6",">=7"))
Pandas中进行区间切分使用的是cut()方法,方法中有个bins参数来指明区间

下面看看官网上对cut函数的详解
pandas.cut(x, bins, right: bool = True, labels=None, retbins: bool = False,
precision: int = 3, include_lowest: bool = False, duplicates: str = 'raise')right == True (the default), then the bins [1, 2, 3, 4] indicate (1,2], (2,3], (3,4]. This argument is ignored when bins is an IntervalIndex.



不需要事先指明切分区间,只需要指明切分的份数即可,依据的原则是每个份数中的数据尽可能相等


Excel直接在确定要加入的某行或者列的前面,在菜单栏中选择加入即可

Python中通过insert方法实现:指明要插入的位置、插入后新列的列名、以及要插入的数据
df.insert(2,"score",np.random.randint(80,100,10)) # 第2列之后插入名为score的一列数据
pandas中还可以通过直接给某列字段赋值的方式实现

行列互换实际上就是转置的意思

转置后的效果图

pandas中的转置只需要调用.T方法即可

所谓的索引重塑就是将原来的索引重新进行构造。两种常见的表示数据的结构:


把数据从表格型数据转换到树形数据的过程,称之为重塑reshape
该过程在Excel中无法实现,在pandas中是通过\color{red}{stack}方法实现的

将树形数据转成表格型数据

长表:很多行记录
宽表:属性特别多
Excel中的长宽表转换是直接通过复制和粘贴实现的。Python中的实现是通过stack()和melt()方法。在转换的过程中,宽表和长表中必须要有相同的列。比如将下图的宽表转成长表
宽表:

长表:



主要参数及解释
Name | Description | Type/Default Value | Required / Optional |
|---|---|---|---|
frame | DataFrame | Required | |
id_vars | Column(s) to use as identifier variables. | tuple, list, or ndarray | Optional |
value_vars | Column(s) to unpivot. If not specified, uses all columns that are not set as id_vars. | tuple, list, or ndarray | Optional |
var_name | Name to use for the ‘variable’ column. If None it uses frame.columns.name or ‘variable’. | scalar | Required |
value_name | Name to use for the ‘value’ column. | scalar Default Value: ‘value’ | Required |
col_level | If columns are a MultiIndex then use this level to melt. | int or string | Optional |
