pandas进阶
pandas是基于numpy构建的库,在数据处理方面可以把它理解为numpy的加强版,由于numpy主要用于科学计算,特长不在于数据处理,我们平常处理的数据一般带有列标签和index索引,这时pandas作为数据分析包而被开发出来。
pandas数据结构(Series/DataFrame)
一、Series
1、Series创建
Series类似一维数组的数据结构,由一组数据(各种numpy数据类型)和与之关联的数据标签(索引)组成,结构相当于定长有序的字典,index和value之间相互独立.
import pandas as pd
import numpy as np
# 创建Series
a1 = pd.Series([1, 2, 3]) # 数组生成Series
a1
0 1
1 2
2 3
dtype: int64
a2 = pd.Series(np.array([1, 2, 3])) # numpy数组生成Series
a2
0 1
1 2
2 3
dtype: int32
a3 = pd.Series([1, 2, 3], index=["index1", "index2", "index3"]) # 指定标签index生成
a3
index1 1
index2 2
index3 3
dtype: int64
a4 = pd.Series({"index1": 1, "index2": 2, "index3": 3}) # 字典生成Series
a4
index1 1
index2 2
index3 3
dtype: int64
a5 = pd.Series({"index": 1, "index2": 2, "index3": 3},
index=["index1", "index2", "index3"]) # 字典生成Series,指定index,不匹配部分为NaN
a5
index1 NaN
index2 2.0
index3 3.0
dtype: float64
a6 = pd.Series(10, index=["index1", "index2", "index3"])
a6
index1 10
index2 10
index3 10
dtype: int64
2、Series属性
可以把Series看成一个定长的有序字典
可以通过shape(维度),size(长度),index(键),values(值)等得到series的属性
a1 = pd.Series([1, 2, 3])
a1.index # Series索引
RangeIndex(start=0, stop=3, step=1)
a1.values # Series数值
array([1, 2, 3], dtype=int64)
a1.name = "population" # 指定Series名字
a1.index.name = "state" # 指定Series索引名字
a1
state
0 1
1 2
2 3
Name: population, dtype: int64
a1.shape
(3,)
a1.size
3
3、Series查找元素
loc为显示切片(通过键),iloc为隐式切片(通过索引)
访问单个元素
s[indexname]
s.loc[indexname] 推荐
s[loc]
s.iloc[loc] 推荐<
访问多个元素
s[[indexname1,indexname2]]
s.loc[[indexname1,indexname2]] 推荐
s[[loc1,loc2]]
s.iloc[[loc1,loc2]] 推荐
a3 = pd.Series([1, 2, 3], index=["index1", "index2", "index3"])
a3
index1 1
index2 2
index3 3
dtype: int64
a3["index1"]
1
a3.loc['index1']
1
a3[1]
2
a3.iloc[1]
2
a3[['index1','index2']]
index1 1
index2 2
dtype: int64
a3.loc[['index1','index2']]
index1 1
index2 2
dtype: int64
a3[[1,2]]
index2 2
index3 3
dtype: int64
a3.iloc[[1,2]]
index2 2
index3 3
dtype: int64
a3[a3 > np.mean(a3)] # 布尔值查找元素
index3 3
dtype: int64
a3[0:2] # 绝对位置切片
index1 1
index2 2
dtype: int64
a3["index1":"index2"] # 索引切片
index1 1
index2 2
dtype: int64
4、Series修改元素
# 修改元素
a3["index3"] = 100 # 按照索引修改元素
a3
index1 1
index2 2
index3 100
dtype: int64
a3[2] = 1000 # 按照绝对位置修改元素
a3
index1 1
index2 2
index3 1000
dtype: int64
5、Series添加元素
# 添加元素
a3["index4"] = 10 # 按照索引添加元素
a3
index1 1
index2 2
index3 1000
index4 10
dtype: int64
6、Series删除元素
a3.drop(["index4", "index3"], inplace=True) # inplace=True表示作用在当前Series
a3
index1 1
index2 2
dtype: int64
7、Series方法
a3 = pd.Series([1, 2, 3], index=["index1", "index2", "index3"])
a3["index3"] = np.NaN # 添加元素
a3
index1 1.0
index2 2.0
index3 NaN
dtype: float64
a3.isnull() # 判断Series是否有缺失值
index1 False
index2 False
index3 True
dtype: bool
a3.notnull() # 判断Series是否没有缺失值
index1 True
index2 True
index3 False
dtype: bool
"index1" in a3 # 判断Series中某个索引是否存在
True
a3.isin([1,2]) # 判断Series中某个值是否存在
index1 True
index2 True
index3 False
dtype: bool
a3.unique() # 统计Series中去重元素
array([ 1., 2., nan])
a3.value_counts() # 统计Series中去重元素和个数
2.0 1
1.0 1
dtype: int64
二、Dataframe
DataFrame是一个【表格型】的数据结构,可以看做是【由Series组成的字典】(共用同一个索引)。DataFrame由按一定顺序排列的多列数据组成。设计初衷是将Series的使用场景从一维拓展到多维。DataFrame既有行索引,也有列索引。
行索引:index
列索引:columns
值:values(numpy的二维数组)
1、创建DataFrame
1.1通过字典创建
data = {"color": ["green", "red", "blue", "black", "yellow"], "price": [1, 2, 3, 4, 5]}
dataFrame1 = pd.DataFrame(data=data) # 通过字典创建
dataFrame1
| color | price | |
|---|---|---|
| 0 | green | 1 |
| 1 | red | 2 |
| 2 | blue | 3 |
| 3 | black | 4 |
| 4 | yellow | 5 |
dataFrame2 = pd.DataFrame(data=data, index=["index1", "index2", "index3", "index4", "index5"])
dataFrame2
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
| index3 | blue | 3 |
| index4 | black | 4 |
| index5 | yellow | 5 |
dataFrame3 = pd.DataFrame(data=data, index=["index1", "index2", "index3", "index4", "index5"],
columns=["price"]) # 指定列索引
dataFrame3
| price | |
|---|---|
| index1 | 1 |
| index2 | 2 |
| index3 | 3 |
| index4 | 4 |
| index5 | 5 |
dataFrame4 = pd.DataFrame(data=np.arange(12).reshape(3, 4)) # 通过numpy数组创建
dataFrame4
| 0 | 1 | 2 | 3 | |
|---|---|---|---|---|
| 0 | 0 | 1 | 2 | 3 |
| 1 | 4 | 5 | 6 | 7 |
| 2 | 8 | 9 | 10 | 11 |
dic = {
'张三':[150,150,150,300],
'李四':[0,0,0,0]
}
pd.DataFrame(data=dic,index=['语文','数学','英语','理综'])
| 张三 | 李四 | |
|---|---|---|
| 语文 | 150 | 0 |
| 数学 | 150 | 0 |
| 英语 | 150 | 0 |
| 理综 | 300 | 0 |
data = [[0,150],[0,150],[0,150],[0,300]]
index = ['语文','数学','英语','理综']
columns = ['李四','张三']
pd.DataFrame(data=data,index=index,columns=columns)
| 李四 | 张三 | |
|---|---|---|
| 语文 | 0 | 150 |
| 数学 | 0 | 150 |
| 英语 | 0 | 150 |
| 理综 | 0 | 300 |
1.2通过Series创建
cars = pd.Series({"Beijing": 300000, "Shanghai": 350000, "Shenzhen": 300000, "Tianjian": 200000, "Guangzhou": 250000,
"Chongqing": 150000})
cars
Beijing 300000
Shanghai 350000
Shenzhen 300000
Tianjian 200000
Guangzhou 250000
Chongqing 150000
dtype: int64
cities = {"Shanghai": 90000, "Foshan": 4500, "Dongguan": 5500, "Beijing": 6600, "Nanjing": 8000, "Lanzhou": None}
apts = pd.Series(cities, name="price")
apts
Shanghai 90000.0
Foshan 4500.0
Dongguan 5500.0
Beijing 6600.0
Nanjing 8000.0
Lanzhou NaN
Name: price, dtype: float64
df = pd.DataFrame({"apts": apts, "cars": cars})
df
| apts | cars | |
|---|---|---|
| Beijing | 6600.0 | 300000.0 |
| Chongqing | NaN | 150000.0 |
| Dongguan | 5500.0 | NaN |
| Foshan | 4500.0 | NaN |
| Guangzhou | NaN | 250000.0 |
| Lanzhou | NaN | NaN |
| Nanjing | 8000.0 | NaN |
| Shanghai | 90000.0 | 350000.0 |
| Shenzhen | NaN | 300000.0 |
| Tianjian | NaN | 200000.0 |
1.3通过dicts的list来构建Dataframe
data = [{"Beijing": 1000, "Shanghai": 2500, "Nanjing": 9850}, {"Beijing": 5000, "Shanghai": 4600, "Nanjing": 7000}]
pd.DataFrame(data)
| Beijing | Nanjing | Shanghai | |
|---|---|---|---|
| 0 | 1000 | 9850 | 2500 |
| 1 | 5000 | 7000 | 4600 |
2、查找DataFrame中的元素
data = {"color": ["green", "red", "blue", "black", "yellow"], "price": [1, 2, 3, 4, 5]}
dataFrame2 = pd.DataFrame(data=data, index=["index1", "index2", "index3", "index4", "index5"])
dataFrame2
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
| index3 | blue | 3 |
| index4 | black | 4 |
| index5 | yellow | 5 |
dataFrame2.columns # 查找dataFrame中所有列标签
Index(['color', 'price'], dtype='object')
dataFrame2.index # 查找dataFrame中的所有行标签
Index(['index1', 'index2', 'index3', 'index4', 'index5'], dtype='object')
dataFrame2.values # 查找dataFrame中的所有值
array([['green', 1],
['red', 2],
['blue', 3],
['black', 4],
['yellow', 5]], dtype=object)
dataFrame2["color"]["index1"] # 索引查找数值(先列后行,否则报错)
'green'
dataFrame2.at["index1", "color"] # 索引查找数值(先行后列,否则报错)
'green'
dataFrame2.iat[0, 1] # 绝对位置查找数值
1
3、查找DataFrame中某一行/列元素
data = {"color": ["green", "red", "blue", "black", "yellow"], "price": [1, 2, 3, 4, 5]}
dataFrame2 = pd.DataFrame(data=data, index=["index1", "index2", "index3", "index4", "index5"])
dataFrame2
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
| index3 | blue | 3 |
| index4 | black | 4 |
| index5 | yellow | 5 |
dataFrame2.loc["index1"] # 查找一行元素
color green
price 1
Name: index1, dtype: object
dataFrame2.iloc[0] # 查找一行元素(绝对位置)
color green
price 1
Name: index1, dtype: object
dataFrame2.iloc[0:2] # 通过iloc方法可以拿到行和列,直接按照index的顺序来取。# 可以当做numpy的ndarray的二维数组来操作。
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
dataFrame2.loc[:, "price"] # 查找一列元素
index1 1
index2 2
index3 3
index4 4
index5 5
Name: price, dtype: int64
dataFrame2.iloc[:, 0] # 查找一列元素(绝对位置)
index1 green
index2 red
index3 blue
index4 black
index5 yellow
Name: color, dtype: object
dataFrame2.values[0] # 查找一行元素
array(['green', 1], dtype=object)
dataFrame2["price"] # 查找一列元素,#通过列名的方式,查找列,不能查找行
index1 1
index2 2
index3 3
index4 4
index5 5
Name: price, dtype: int64
dataFrame2["color"]
index1 green
index2 red
index3 blue
index4 black
index5 yellow
Name: color, dtype: object
4、查找DataFrame中的多行/列元素
dataFrame2.head(5) # 查看前5行元素
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
| index3 | blue | 3 |
| index4 | black | 4 |
| index5 | yellow | 5 |
dataFrame2.tail(5) # 查看后5行元素
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
| index3 | blue | 3 |
| index4 | black | 4 |
| index5 | yellow | 5 |
dataFrame2["index1":"index4"] # 切片多行
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
| index3 | blue | 3 |
| index4 | black | 4 |
dataFrame2[0:4] # 切片多行
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
| index3 | blue | 3 |
| index4 | black | 4 |
dataFrame2.loc[["index1", "index2"]] # 多行
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
dataFrame2.iloc[[0, 1]] # 多行
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
dataFrame2.loc[:, ["price"]] # 多列
| price | |
|---|---|
| index1 | 1 |
| index2 | 2 |
| index3 | 3 |
| index4 | 4 |
| index5 | 5 |
dataFrame2.iloc[:, [0, 1]] # 多列
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
| index3 | blue | 3 |
| index4 | black | 4 |
| index5 | yellow | 5 |
dataFrame2.loc[["index1", "index3"], ["price"]] # 索引查找
| price | |
|---|---|
| index1 | 1 |
| index3 | 3 |
dataFrame2.iloc[[1, 2], [0]] # 绝对位置查找
| color | |
|---|---|
| index2 | red |
| index3 | blue |
5、添加一行/列元素
dataFrame2.loc["index6"] = ["pink", 3]
dataFrame2
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
| index3 | blue | 3 |
| index4 | black | 4 |
| index5 | yellow | 5 |
| index6 | pink | 3 |
dataFrame2.loc["index6"]=10
dataFrame2
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
| index3 | blue | 3 |
| index4 | black | 4 |
| index5 | yellow | 5 |
| index6 | 10 | 10 |
dataFrame2.iloc[5] = 10
dataFrame2
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
| index3 | blue | 3 |
| index4 | black | 4 |
| index5 | yellow | 5 |
| index6 | 10 | 10 |
dataFrame2.loc["index7"] = 100
dataFrame2
| color | price | |
|---|---|---|
| index1 | green | 1 |
| index2 | red | 2 |
| index3 | blue | 3 |
| index4 | black | 4 |
| index5 | yellow | 5 |
| index6 | 10 | 10 |
| index7 | 100 | 100 |
dataFrame2.loc[:, "size"] = "small"
dataFrame2
| color | price | size | |
|---|---|---|---|
| index1 | green | 1 | small |
| index2 | red | 2 | small |
| index3 | blue | 3 | small |
| index4 | black | 4 | small |
| index5 | yellow | 5 | small |
| index6 | 10 | 10 | small |
| index7 | 100 | 100 | small |
dataFrame2.iloc[:, 2] = 10
dataFrame2
| color | price | size | |
|---|---|---|---|
| index1 | green | 1 | 10 |
| index2 | red | 2 | 10 |
| index3 | blue | 3 | 10 |
| index4 | black | 4 | 10 |
| index5 | yellow | 5 | 10 |
| index6 | 10 | 10 | 10 |
| index7 | 100 | 100 | 10 |
6、修改元素
dataFrame2.loc["index1", "price"] = 100
dataFrame2
| color | price | size | |
|---|---|---|---|
| index1 | green | 100 | 10 |
| index2 | red | 2 | 10 |
| index3 | blue | 3 | 10 |
| index4 | black | 4 | 10 |
| index5 | yellow | 5 | 10 |
| index6 | 10 | 10 | 10 |
| index7 | 100 | 100 | 10 |
dataFrame2.iloc[0, 1] = 10
dataFrame2
| color | price | size | |
|---|---|---|---|
| index1 | green | 10 | 10 |
| index2 | red | 2 | 10 |
| index3 | blue | 3 | 10 |
| index4 | black | 4 | 10 |
| index5 | yellow | 5 | 10 |
| index6 | 10 | 10 | 10 |
| index7 | 100 | 100 | 10 |
dataFrame2.at["index1", "price"] = 100
dataFrame2
| color | price | size | |
|---|---|---|---|
| index1 | green | 100 | 10 |
| index2 | red | 2 | 10 |
| index3 | blue | 3 | 10 |
| index4 | black | 4 | 10 |
| index5 | yellow | 5 | 10 |
| index6 | 10 | 10 | 10 |
| index7 | 100 | 100 | 10 |
dataFrame2.iat[0, 1] = 1000
dataFrame2
| color | price | size | |
|---|---|---|---|
| index1 | green | 1000 | 10 |
| index2 | red | 2 | 10 |
| index3 | blue | 3 | 10 |
| index4 | black | 4 | 10 |
| index5 | yellow | 5 | 10 |
| index6 | 10 | 10 | 10 |
| index7 | 100 | 100 | 10 |
7、删除元素
dataFrame2.drop(["index6", "index7"], inplace=True) # inplace=True表示作用在原数组
dataFrame2
| color | price | size | |
|---|---|---|---|
| index1 | green | 1000 | 10 |
| index2 | red | 2 | 10 |
| index3 | blue | 3 | 10 |
| index4 | black | 4 | 10 |
| index5 | yellow | 5 | 10 |
a=dataFrame2.drop(["price"], axis=1, inplace=False)
dataFrame2
| color | price | |
|---|---|---|
| index1 | green | 1000 |
| index2 | red | 2 |
| index3 | blue | 3 |
| index4 | black | 4 |
| index5 | yellow | 5 |
a
| color | |
|---|---|
| index1 | green |
| index2 | red |
| index3 | blue |
| index4 | black |
| index5 | yellow |
8. 处理NaN数据
dates = pd.date_range('20180101', periods=3)
df = pd.DataFrame(np.arange(12).reshape((3, 4)),
index=dates, columns=['a', 'b', 'c', 'd'])
df.iloc[1, 1], df.iloc[2, 2] = np.nan, np.nan
df
| a | b | c | d | |
|---|---|---|---|---|
| 2018-01-01 | 0 | 1.0 | 2.0 | 3 |
| 2018-01-02 | 4 | NaN | 6.0 | 7 |
| 2018-01-03 | 8 | 9.0 | NaN | 11 |
8.1删除NaN数据
re=df.dropna(axis=1, inplace=False) # inplace默认为false
df
| a | b | c | d | |
|---|---|---|---|---|
| 2018-01-01 | 0 | 1.0 | 2.0 | 3 |
| 2018-01-02 | 4 | NaN | 6.0 | 7 |
| 2018-01-03 | 8 | 9.0 | NaN | 11 |
re
| a | d | |
|---|---|---|
| 2018-01-01 | 0 | 3 |
| 2018-01-02 | 4 | 7 |
| 2018-01-03 | 8 | 11 |
8.2填充NaN数据
re2 = df.fillna(value='*')
re2
| a | b | c | d | |
|---|---|---|---|---|
| 2018-01-01 | 0 | 1 | 2 | 3 |
| 2018-01-02 | 4 | * | 6 | 7 |
| 2018-01-03 | 8 | 9 | * | 11 |
8.3 检查是否存在NaN
df.isnull()
| a | b | c | d | |
|---|---|---|---|---|
| 2018-01-01 | False | False | False | False |
| 2018-01-02 | False | True | False | False |
| 2018-01-03 | False | False | True | False |
9.合并DataFrame
9.1 concat函数
df1 = pd.DataFrame(np.ones((3, 4)) * 0, columns=['a', 'b', 'c', 'd'])
df1
| a | b | c | d | |
|---|---|---|---|---|
| 0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 1 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2 | 0.0 | 0.0 | 0.0 | 0.0 |
df2 = pd.DataFrame(np.ones((3, 4)) * 1, columns=['a', 'b', 'c', 'd'])
df2
| a | b | c | d | |
|---|---|---|---|---|
| 0 | 1.0 | 1.0 | 1.0 | 1.0 |
| 1 | 1.0 | 1.0 | 1.0 | 1.0 |
| 2 | 1.0 | 1.0 | 1.0 | 1.0 |
df3 = pd.DataFrame(np.ones((3, 4)) * 2, columns=['a', 'b', 'c', 'd'])
df3
| a | b | c | d | |
|---|---|---|---|---|
| 0 | 2.0 | 2.0 | 2.0 | 2.0 |
| 1 | 2.0 | 2.0 | 2.0 | 2.0 |
| 2 | 2.0 | 2.0 | 2.0 | 2.0 |
# ignore_index=True将重新对index排序
pd.concat([df1, df2, df3], axis=0, ignore_index=True)
| a | b | c | d | |
|---|---|---|---|---|
| 0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 1 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2 | 0.0 | 0.0 | 0.0 | 0.0 |
| 3 | 1.0 | 1.0 | 1.0 | 1.0 |
| 4 | 1.0 | 1.0 | 1.0 | 1.0 |
| 5 | 1.0 | 1.0 | 1.0 | 1.0 |
| 6 | 2.0 | 2.0 | 2.0 | 2.0 |
| 7 | 2.0 | 2.0 | 2.0 | 2.0 |
| 8 | 2.0 | 2.0 | 2.0 | 2.0 |
# ignore_index=True将重新对index排序
pd.concat([df1, df2, df3], axis=0, ignore_index=False)
| a | b | c | d | |
|---|---|---|---|---|
| 0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 1 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2 | 0.0 | 0.0 | 0.0 | 0.0 |
| 0 | 1.0 | 1.0 | 1.0 | 1.0 |
| 1 | 1.0 | 1.0 | 1.0 | 1.0 |
| 2 | 1.0 | 1.0 | 1.0 | 1.0 |
| 0 | 2.0 | 2.0 | 2.0 | 2.0 |
| 1 | 2.0 | 2.0 | 2.0 | 2.0 |
| 2 | 2.0 | 2.0 | 2.0 | 2.0 |
join参数用法
df1 = pd.DataFrame(np.ones((3, 4)) * 0, columns=['a', 'b', 'c', 'd'], index=[1, 2, 3])
df2 = pd.DataFrame(np.ones((3, 4)) * 1, columns=['b', 'c', 'd', 'e'], index=[2, 3, 4])
# join默认为'outer',不共有的列用NaN填充
pd.concat([df1, df2], sort=False, join='outer')
| a | b | c | d | e | |
|---|---|---|---|---|---|
| 1 | 0.0 | 0.0 | 0.0 | 0.0 | NaN |
| 2 | 0.0 | 0.0 | 0.0 | 0.0 | NaN |
| 3 | 0.0 | 0.0 | 0.0 | 0.0 | NaN |
| 2 | NaN | 1.0 | 1.0 | 1.0 | 1.0 |
| 3 | NaN | 1.0 | 1.0 | 1.0 | 1.0 |
| 4 | NaN | 1.0 | 1.0 | 1.0 | 1.0 |
# join='inner'只合并共有的列
pd.concat([df1, df2], sort=False, join='inner',ignore_index=True)
| b | c | d | |
|---|---|---|---|
| 0 | 0.0 | 0.0 | 0.0 |
| 1 | 0.0 | 0.0 | 0.0 |
| 2 | 0.0 | 0.0 | 0.0 |
| 3 | 1.0 | 1.0 | 1.0 |
| 4 | 1.0 | 1.0 | 1.0 |
| 5 | 1.0 | 1.0 | 1.0 |
join_axes参数用法
# 按照df1的index进行合并
pd.concat([df1, df2], axis=1, join_axes=[df1.index])
| a | b | c | d | b | c | d | e | |
|---|---|---|---|---|---|---|---|---|
| 1 | 0.0 | 0.0 | 0.0 | 0.0 | NaN | NaN | NaN | NaN |
| 2 | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 | 1.0 | 1.0 | 1.0 |
| 3 | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 | 1.0 | 1.0 | 1.0 |
9.2 append函数¶
df1 = pd.DataFrame(np.ones((3, 4)) * 0, columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame(np.ones((3, 4)) * 1, columns=['a', 'b', 'c', 'd']) re = df1.append(df2, ignore_index=True)
re
| a | b | c | d | |
|---|---|---|---|---|
| 0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 1 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2 | 0.0 | 0.0 | 0.0 | 0.0 |
| 3 | 1.0 | 1.0 | 1.0 | 1.0 |
| 4 | 1.0 | 1.0 | 1.0 | 1.0 |
| 5 | 1.0 | 1.0 | 1.0 | 1.0 |
append一组数据
df1 = pd.DataFrame(np.ones((3, 4)) * 0, columns=['a', 'b', 'c', 'd'])
s = pd.Series([4, 4, 4, 4], index=['a', 'b', 'c', 'd']) re = df1.append(s, ignore_index=True)
re
| a | b | c | d | |
|---|---|---|---|---|
| 0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 1 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2 | 0.0 | 0.0 | 0.0 | 0.0 |
| 3 | 4.0 | 4.0 | 4.0 | 4.0 |
9.3 merge函数
基于某一列进行合并
df1 = pd.DataFrame({'A': ['A1', 'A2', 'A3'],
'B': ['B1', 'B2', 'B3'],
'KEY': ['K1', 'K2', 'K3']})
df2 = pd.DataFrame({'C': ['C1', 'C2', 'C3'],
'D': ['D1', 'D2', 'D3'],
'KEY': ['K1', 'K2', 'K3']})
df1
| A | B | KEY | |
|---|---|---|---|
| 0 | A1 | B1 | K1 |
| 1 | A2 | B2 | K2 |
| 2 | A3 | B3 | K3 |
df2
| C | D | KEY | |
|---|---|---|---|
| 0 | C1 | D1 | K1 |
| 1 | C2 | D2 | K2 |
| 2 | C3 | D3 | K3 |
re = pd.merge(df1, df2, on='KEY')
re
| A | B | KEY | C | D | |
|---|---|---|---|---|---|
| 0 | A1 | B1 | K1 | C1 | D1 |
| 1 | A2 | B2 | K2 | C2 | D2 |
| 2 | A3 | B3 | K3 | C3 | D3 |
基于某两列进行合并
df1 = pd.DataFrame({'A': ['A1', 'A2', 'A3'],
'B': ['B1', 'B2', 'B3'],
'KEY1': ['K1', 'K2', 'K0'],
'KEY2': ['K0', 'K1', 'K3']})
df2 = pd.DataFrame({'C': ['C1', 'C2', 'C3'],
'D': ['D1', 'D2', 'D3'],
'KEY1': ['K0', 'K2', 'K1'],
'KEY2': ['K1', 'K1', 'K0']})
# how:['left','right','outer','inner']
re = pd.merge(df1, df2, on=['KEY1', 'KEY2'], how='inner')
re
| A | B | KEY1 | KEY2 | C | D | |
|---|---|---|---|---|---|---|
| 0 | A1 | B1 | K1 | K0 | C3 | D3 |
| 1 | A2 | B2 | K2 | K1 | C2 | D2 |
按index合并
df1 = pd.DataFrame({'A': ['A1', 'A2', 'A3'],
'B': ['B1', 'B2', 'B3']},
index=['K0', 'K1', 'K2'])
df2 = pd.DataFrame({'C': ['C1', 'C2', 'C3'],
'D': ['D1', 'D2', 'D3']},
index=['K0', 'K1', 'K3'])
re = pd.merge(df1, df2, left_index=True, right_index=True, how='outer')
re
| A | B | C | D | |
|---|---|---|---|---|
| K0 | A1 | B1 | C1 | D1 |
| K1 | A2 | B2 | C2 | D2 |
| K2 | A3 | B3 | NaN | NaN |
| K3 | NaN | NaN | C3 | D3 |
为列加后缀
df_boys = pd.DataFrame({'id': ['1', '2', '3'],
'age': ['23', '25', '18']})
df_girls = pd.DataFrame({'id': ['1', '2', '3'],
'age': ['18', '18', '18']})
re = pd.merge(df_boys, df_girls, on='id', suffixes=['_boys', '_girls'])
re
| id | age_boys | age_girls | |
|---|---|---|---|
| 0 | 1 | 23 | 18 |
| 1 | 2 | 25 | 18 |
| 2 | 3 | 18 | 18 |
pandas进阶的更多相关文章
- Pandas进阶笔记 (一) Groupby 重难点总结
如果Pandas只是能把一些数据变成 dataframe 这样优美的格式,那么Pandas绝不会成为叱咤风云的数据分析中心组件.因为在数据分析过程中,描述数据是通过一些列的统计指标实现的,分析结果也需 ...
- 程序员用于机器学习编程的Python 数据处理库 pandas 进阶教程
数据访问 在入门教程中,我们已经使用过访问数据的方法.这里我们再集中看一下. 注:这里的数据访问方法既适用于Series,也适用于DataFrame. **基础方法:[]和. 这是两种最直观的方法,任 ...
- Pandas进阶笔记 (0)为什么写这个系列
使用Pandas数年之久了,从最早的0.17版本开始接触Pandas,到现在0.25版本,踩过不少坑,面对各种稀奇古怪的bug抓耳挠腮.每每想要解决bug,或者想要实现一个特定的数据操作需求,首先想到 ...
- Pandas进阶之提升运行效率
前言 如果你现在正在学习数据分析,或者正在从事数据分析行业,肯定会处理一些大数据集.pandas就是这些大数据集的一个很好的处理工具.那么pandas到底是什么呢?官方文档上说: " 快速, ...
- Pandas进阶之DataFrame多级索引
多级索引:在一个轴上有多个(两个以上)的索引,能够以低维度形式来表示高维度的数据.单级索引是Index对象,多级索引是MultiIndex对象. 一.创建多级索引 方法一:隐式创建,即给DataFra ...
- 学习笔记之pandas
Python Data Analysis Library — pandas: Python Data Analysis Library https://pandas.pydata.org/ panda ...
- Python 数据处理库pandas教程(最后附上pandas_datareader使用实例)
0 简单介绍 pandas是一个Python语言的软件包,在我们使用Python语言进行机器学习编程的时候,这是一个非常常用的基础编程库.本文是对它的一个入门教程. pandas提供了快速,灵活和富有 ...
- 前置机器学习(四):一文掌握Pandas用法
Pandas提供快速,灵活和富于表现力的数据结构,是强大的数据分析Python库. 本文收录于机器学习前置教程系列. 一.Series和DataFrame Pandas建立在NumPy之上,更多Num ...
- python做量化交易干货分享
http://www.newsmth.NET/nForum/#!article/Python/128763 最近程序化交易很热,量化也是我很感兴趣的一块. 国内量化交易的平台有几家,我个人比较喜欢用的 ...
随机推荐
- Arthas随笔
目录 Arthas 安装Java 安装 Arthas Arthas 命令及示例 源码分析 Arthas 安装Java 下载jdk 注意 下载的JDK版本要与linux操作系统相匹配,否则汇报No su ...
- Mysql 创建函数出现This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA
This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary mys ...
- ERROR:imshow、Mat、waitkey找不到标识符(opencv)
可以发现imshow.Mat.waitkey这三个都是opencv相关的. 在添加了相关库文件后还是有问题. #include "stdafx.h" #include <st ...
- C# 开发COM组件供c++使用
C# 开发COM组件供c++使用 Microsoft在解决和以往的COM和SDK开发技术之间的互操作性(Interoperability)方面做了很多的工作,其中包括COM和.NET对象之间的相互调用 ...
- 使用 circleci 自动部署 vuepress 到 github
概述 今天我想把博客什么的搬到 github 的 vuepress 上面.但是每次提交 md 文件需要手动打包然后再提交到 github 的 gh-pages,非常麻烦.所以我去研究了一下用 circ ...
- Python Module_Socket_网络编程
目录 目录 Socket 套接字 套接字的原理 套接字的数据处理方式 套接字类型 Socket 标准函数 ServerSocket 标准函数 ClientSocket 标准函数 公有标准函数 Sock ...
- Java使用JDBC连接Impala
前段时间,有一个项目在连接Impala的时候,可以测试连接成功,但是查询不出表.但是通过impala-shell的时候,是可以查询出来的,我觉的这种方式查询出来的话,可能和jdbc的方式不一样,因为i ...
- 把自己活成AI
干啥都失败,所以从0重新开始. 把自己活成AI 准则1:一件事的对错,只代表这件事本身.多一点的解释都是错误. 准则2:大多数人默认遵守的就是规则和法律.大多数人默认承认的就是道德. 然后取其和法律的 ...
- 学用 TStringGrid [6] - Options
本例运行效果图: 一般修改 TStringGrid 的 Options 直接在设计时选一下 True 或 False 就行了; 代码中可以像下面操作: StringGrid1.Options := ...
- django连接数据库的类型
字段类型 django的models里面字段类型除了上面的常用的 models.CharField和models.IntegerField,还有更多的类型 1.models.AutoField 自增列 ...