Pandas数据结构
Series数据结构
创建Series
传入列表
import pandas as pd
S1 = pd.Series(['a','b','c','d'])
S1
>>>
0 a
1 b
2 c
3 d
dtype: object
指定索引
index参数自定义索引
import pandas as pd
S1 = pd.Series(['a','b','c','d'],index = [1,2,3,4])
S1
>>>
1 a
2 b
3 c
4 d
dtype: object
传入字典
import pandas as pd
S1 = pd.Series({'a':1,'b':2,'c':3,'d':4})
S1
>>>
a 1
b 2
c 3
d 4
dtype: int64
- key 为数据标签
- value 为数据值
获取Series行、列索引
index获取Series索引
S1.index
>>>
Index(['a', 'b', 'c', 'd'], dtype='object')
values获取Series值
S1.values
>>>
array([1, 2, 3, 4])
DataFrame 数据结构
创建DataFrame
传入列表
import pandas as pd
df1 = pd.DataFrame(['a','b','c','d'])
df1
>>>
0
0 a
1 b
2 c
3 d
传入嵌套列表&元祖
import pandas as pd
df1 = pd.DataFrame([['a','A'],['b','B'],['c','C'],['d','D']])
df1
>>>
0 1
0 a A
1 b B
2 c C
3 d D
import pandas as pd
df1 = pd.DataFrame([('a','A'),('b','B'),('c','C'),('d','D')])
df1
>>>
0 1
0 a A
1 b B
2 c C
3 d D
指定行、列索引
index自定义行索引,columns自定义列索引
import pandas as pd
df1 = pd.DataFrame([('a','A'),('b','B'),('c','C'),('d','D')],columns = ['小写','大写'],index = ['一','二','三','四'])
df1
>>>
小写 大写
一 a A
二 b B
三 c C
四 d D
传入字典
data = {'小写':['a','b','c','d'],'大写':['A','B','C','D']}
df = pd.DataFrame(data)
df
>>>
小写 大写
0 a A
1 b B
2 c C
3 d D
- key 为列索引
- 行索引默认从0开始,也可以使用index自定义
data = {'小写':['a','b','c','d'],'大写':['A','B','C','D']}
df = pd.DataFrame(data,index = ['一','二','三','四'])
df
>>>
小写 大写
一 a A
二 b B
三 c C
四 d D
获取DataFrame 行、列索引
columns获取DataFrame列索引
df.columns
>>>
Index(['小写', '大写'], dtype='object')
index获取DataFrame行索引
df.index
>>>
Index(['一', '二', '三', '四'], dtype='object')