# 两种数据结构:Series和DataFrame
# 创建
import pandas as pd
s1 = pd.Series(['丁一', '王二', '张三'])
print(s1)
print(s1[1])
二维数据表格DataFrame的创建与索引的修改
# 1.DataFrame的创建
# (1)通过列表创建
import pandas as pd
a = pd.DataFrame([[1,2], [3,4], [5,6]])
print(a)
0 1 # 列号
0 1 2
1 3 4
2 5 6
#行号 1、2、3、4、5、6是内容
# 自定义列索引和行索引的名称
import pandas as pd
a = pd.DataFrame([[1,2], [3,4], [5,6]], columns=['date', 'score'], index=['A', 'B', 'C'])
print(a)
date score
A 1 2
B 3 4
C 5 6
columns代表列索引名称,index代表行索引名称
# 自定义列索引和行索引的名称
import pandas as pd
a = pd.DataFrame()
date = [1, 3, 5]
score = [2, 4, 6]
a['date'] = date
a['score'] = score
print(a)
# 要保证date列表和score列表的长度一致,否则会报错
# (2)通过字典创建
# 默认字典键为索引
import pandas as pd
b = pd.DataFrame({'a': [1, 3, 5], 'b': [2, 4, 6]}, index = ['x', 'y', 'z'])
print(b)
a b
x 1 2
y 3 4
z 5 6
# 让字典键变为行索引
c = pd.DataFrame.from_dict({'a': [1, 3, 5], 'b': [2, 4, 6]}, orient='index')
print(c)
0 1 2
a 1 3 5
b 2 4 6
(3)通过二维数组创建
import numpy as np
import pandas as pd
d = pd.DataFrame(np.arange(12).reshape(3, 4), index=[1, 2, 3], columns = ['A', 'B', 'C', 'D'])
print(d) # 3行4列
A B C D
1 0 1 2 3
2 4 5 6 7
3 8 9 10 11
# DataFrame索引的修改
import pandas as pd
a = pd.DataFrame([[1, 2], [3, 4], [5, 6]], columns=['date', 'score'], index= ['A', 'B', 'C'])
a.index.name = '公司'
print(a)
公司
A 1 2
B 3 4
C 5 6
# 索引重命名
a.rename(index={'A': '万科', 'B': '阿里', 'C': '百度'}, columns={'date':'日期','score':'分数'}, inplace=True)
a = a.reset_index()
a = a.set_index('日期')
print(a)
日期 分数
公司
万科 1 2
阿里 3 4
百度 5 6
# reset_index()
公司 日期 分数
0 万科 1 2
1 阿里 3 4
2 百度 5 6
公司 分数
日期
1 万科 2
3 阿里 4
5 百度 6
# EXCEL文件的读取
import pandas as pd
data = pd.read_excel('data.xlsx')
# pd.read_excel('data.xlsx', sheetname=0, encoding='utf-8')
# sheetname用于指定工作表,可以是工作表名称,也可以是数字(默认为0,即1个工作表)
# encoding用于指定文件编码方式,一般设置为utf-8或GBK
# index_col用于设置某一列为行索引
import pandas as pd
data = pd.DataFrame([[1,2], [3, 4], [5, 6]], columns=['A列', 'B列'])
# data.to_excel('data.xlsx')
# sheetname用于指定工作表名称
# index用于指定是否写入行索引信息,默认为True,即保存行索引信息到输出文件的第1列,或设置为False,则忽略行索引信息
# columns用于指定要写入的列
# encoding用于指定编码方式
# 要将data中的A列数据写入Excel并忽略行索引信息
data.to_excel('data.xlsx', columns=['A列'], index=False)
import numpy as np
import pandas as pd
# 创建一个3行3列的DataFrame,行索引为r1,r2,r3,列索引为c1,c2,c3
data = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=['r1', 'r2', 'r3'], columns=['c1', 'c2', 'c3'])
# 生成1-9个数字
print(data)
'''
c1 c2 c3
r1 1 2 3
r2 4 5 6
r3 7 8 9
'''
data2 = pd.DataFrame(np.arange(1, 10).reshape(3, 3), index=['r1', 'r2', 'r3'], columns=['c1', 'c2', 'c3'])
print(data2)
'''
c1 c2 c3
r1 1 2 3
r2 4 5 6
r3 7 8 9
'''
网友评论