python-pandas创建DataFrame类型
文章目录
1.创建DataFrame类型
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
方法1: 通过列表创建
li = [
[1, 2, 3, 4],
[2, 3, 4, 5]
]
# DataFRame对象里面包含两个索引, 行索引(0轴, axis=0), 列索引(1轴, axis=1)
d1 = pd.DataFrame(data=li, index=['A', 'B'], columns=['views', 'loves', 'comments', 'tranfers'])
print(d1)
方法2: 通过numpy对象创建
narr = np.arange(8).reshape(2, 4)
# DataFRame对象里面包含两个索引, 行索引(0轴, axis=0), 列索引(1轴, axis=1)
d2 = pd.DataFrame(data=narr, index=['A', 'B'], columns=['views', 'loves', 'comments', 'tranfers'])
print(d2)
方法3: 通过字典的方式创建;
dict = {
'views': [1, 2, ],
'loves': [2, 3, ],
'comments': [3, 4, ]
}
d3 = pd.DataFrame(data=dict, index=['粉条', "粉丝"])
print(d3)
日期操作的特例:date_range()
源码:
dates = pd.date_range(start='1/1/2018', end='1/08/2018')
print(dates)
# 行索引
dates = pd.date_range(start='today', periods=6)
# 数据
data_arr = np.random.randn(6, 4)
# 列索引
columns = ['A', 'B', 'C', 'D']
d4 = pd.DataFrame(data_arr, index=dates, columns=columns)
print(d4)
练习:
一维对象: 建立一个以2019年每一天作为索引, 值为随机数;
因为是一维,所以用Series。
dates = pd.date_range(start='1/1/2019', end='12/31/2019', freq='D')
datas = np.random.randn(len(dates))
s1 = pd.Series(datas, index=dates)
print(s1[:3])
2.DataFrame基本操作
先生成二维数组:
import pandas as pd
import numpy as np
narr = np.arange(8).reshape(2, 4)
# DataFRame对象里面包含两个索引, 行索引(0轴, axis=0), 列索引(1轴, axis=1)
d2 = pd.DataFrame(data=narr, index=['A', 'B'], columns=['views', 'loves', 'comments', 'tranfers'])
print(d2)
输出:
views loves comments tranfers
A 0 1 2 3
B 4 5 6 7
1). 查看基础属性
print(d2.shape) # 获取行数和列数;
print(d2.dtypes) # 列数据类型
print(d2.ndim) # 获取数据的维度
print(d2.index) # 行索引
print(d2.columns) # 列索引
print(d2.values, type(d2.values)) # 对象的值, 二维ndarray数组;
输出:
(2, 4)
-----------------------------------
views int64
loves int64
comments int64
tranfers int64
dtype: object
-----------------------------------
2
-----------------------------------
Index(['A', 'B'], dtype='object')
-----------------------------------
Index(['views', 'loves', 'comments', 'tranfers'], dtype='object')
-----------------------------------
[[0 1 2 3]
[4 5 6 7]] <class 'numpy.ndarray'>
2). 数据整体状况的查询
head头部的几行
tail尾部几行
info相关信息的预览
describe快速综合计算结果
print(d2.head(1)) # 显示头部的几行, 默认5行
print(d2.tail(1)) # 显示尾行, 默认5行
输出:
views loves comments tranfers
A 0 1 2 3
views loves comments tranfers
B 4 5 6 7
# 相关信息的预览: 行数, 列数, 列类型, 内存占用
print("info:", d2.info())
输出:
<class 'pandas.core.frame.DataFrame'>
Index: 2 entries, A to B
Data columns (total 4 columns):
views 2 non-null int64
loves 2 non-null int64
comments 2 non-null int64
tranfers 2 non-null int64
dtypes: int64(4)
memory usage: 80.0+ bytes
info: None
# 快速综合用计结果: 计数, 均值, 标准差, 最小值, 1/4位数, 中位数, 3/4位数, 最大值;
print(d2.describe())
输出:
views loves comments tranfers
count 2.000000 2.000000 2.000000 2.000000
mean 2.000000 3.000000 4.000000 5.000000
std 2.828427 2.828427 2.828427 2.828427
min 0.000000 1.000000 2.000000 3.000000
25% 1.000000 2.000000 3.000000 4.000000
50% 2.000000 3.000000 4.000000 5.000000
75% 3.000000 4.000000 5.000000 6.000000
max 4.000000 5.000000 6.000000 7.000000
3). 转置操作.T
print(d2.T)
A B
views 0 4
loves 1 5
comments 2 6
tranfers 3 7
4). 按列进行排序sort_values
按照指定列进行排序, 默认是升序, 如果需要降序显示,设置ascending=False;
print(d2.sort_values(by="views", ascending=False))
5). 切片及查询
取一行:
print(d2[:1]) # 可以实现切片, 但是不能索引;
输出:
views loves comments tranfers
A 0 1 2 3
取一列:
print('1:\n', d2['views']) # 通过标签查询, 获取单列信息
print('2:\n', d2.views) # 和上面是等价的;
1:
A 0
B 4
Name: views, dtype: int64
-----------------------------------
2:
A 0
B 4
Name: views, dtype: int64
取多列:
print(d2[['views', 'comments']]) # 通过标签查询多列信息
输出:
views comments
A 0 2
B 4 6
6). 通过类似索引的方式查询;iloc、loc
- iloc(通过位置进行行数据的获取),
- loc(通过标签索引行数据)
第一行:
print(d2.iloc[0])
输出:
views 0
loves 1
comments 2
tranfers 3
Name: A, dtype: int64
最后一行:
print(d2.iloc[-1:])
输出:
views loves comments tranfers
B 4 5 6 7
取第A行:
print(d2.loc['A'])
输出:
views 0
loves 1
comments 2
tranfers 3
Name: A, dtype: int64
7). 更改pandas的值;
d2.loc['A'] = np.nan
print(d2)
输出:
views loves comments tranfers
A NaN NaN NaN NaN
B 4.0 5.0 6.0 7.0
3.从文件中读写数据
1). csv文件的写入
df = pd.DataFrame(
{'province': ['陕西', '陕西', '四川', '四川', '陕西'],
'city': ['咸阳', '宝鸡', '成都', '成都', '宝鸡'],
'count1': [1, 2, 3, 4, 5],
'count2': [1, 2, 33, 4, 5]
}
)
df.to_csv('doc/csvFile.csv')
print("csv文件保存成功")
2). csv文件的读取
df2 = pd.read_csv('doc/csvFile.csv')
print(df2)
3). excel文件的写入
df2.to_excel("/tmp/excelFile.xlsx", sheet_name="省份统计")
print("excel文件保存成功")
4.groupby分组与聚合
pandas提供了一个灵活高效的groupby功能,
1). 它使你能以一种自然的方式对数据集进行切片、切块、摘要等操作。
2). 根据一个或多个键(可以是函数、数组或DataFrame列>名)拆分pandas对象。
3). 计算分组摘要统计,如计数、平均值、标准差,或用户自定义函数。
import pandas as pd
import numpy as np
df = pd.DataFrame(
{
'province':['陕西','陕西','四川','四川','陕西'],
'city':['咸阳','宝鸡','成都','成都','宝鸡'],
'count1':[1,2,3,4,5],
'count2':[1,2,33,4,5]
}
)
print(df)
输出:
province city count1 count2
0 陕西 咸阳 1 1
1 陕西 宝鸡 2 2
2 四川 成都 3 33
3 四川 成都 4 4
4 陕西 宝鸡 5 5
1)根据某一列的key值进行统计分析;
# 根据省份分析count1信息
grouped = df['count1'].groupby(df['province'])
print(grouped.describe())
输出:
count mean std min 25% 50% 75% max
province
四川 2.0 3.500000 0.707107 3.0 3.25 3.5 3.75 4.0
陕西 3.0 2.666667 2.081666 1.0 1.50 2.0 3.50 5.0
print(grouped.median()) #中位数
输出:
province
四川 3.5
陕西 2.0
grouped = df['count1'].groupby(df['province'])
print(grouped.max())
province
四川 4
陕西 5
2)指定多个key值进行分类聚合;
# 根据省份和城市分析count1信息
grouped = df['count1'].groupby([df['province'],df['city']])
print(grouped)
# <pandas.core.groupby.generic.SeriesGroupBy object at 0x7f65b780b080>
print(grouped.max())
# 四川 成都 4
# 陕西 咸阳 1
# 宝鸡 5
print(grouped.sum())
# 四川 成都 7
# 陕西 咸阳 1
# 宝鸡 7
print(grouped.count()) #城市出现次数
# 四川 成都 2
# 陕西 咸阳 1
# 宝鸡 2