getting_started_0

在这里插入图片描述

import numpy as np
import pandas as pd

Series类似于一维数组,不过添加了索引index

1、从ndarray创建

s = pd.Series(data=np.random.randint(0,5,size=3), index=['a', 'b', 'c'], dtype=int)  # index在默认情况下是012..,自设定的话要保证与data等长
s  # 支持重复index
a    1
b    1
c    3
dtype: int32

2、从字典创建

data_dict = {'world':2, 'hello':1, }
s2 = pd.Series(data_dict)  # 按照插入顺序,低版本可能按照字母序
s2
world    2
hello    1
dtype: int64
s2 = pd.Series(data_dict, index=['a', 'hello', 'world'])  # 按照插入顺序,低版本可能按照字母序
s2
a        NaN
hello    1.0
world    2.0
dtype: float64

3、从标量创建
s3 = pd.Series(5, index=['a', 'b', 'c'])  # 拷贝的次数和index长度相等
s3
a    5
b    5
c    5
dtype: int64

4、像数组一样操作

s[0]  # 索引,返回int32(取决于定义的时候)
1
s[0:3] # 切片,返回series
a    1
b    3
b    0
dtype: int32
s[[2,0]]  # array based index
b    0
a    1
dtype: int32
np.exp(s)
a     2.718282
b    20.085537
b     1.000000
dtype: float64
s.array  # 当不需要index的时候有用
<PandasArray>
[1, 3, 0]
Length: 3, dtype: int32
s.to_numpy()  # 返回真的array
array([1, 3, 0])

5、像字典一样操作

s2
a        NaN
hello    1.0
world    2.0
dtype: float64
s2['hello']
1.0
for i in s2.index:
    print(s2[i])
nan
1.0
2.0
'hello' in s2
True
s2.get('haha', np.asarray(0))  # 第二参数为默认值
array(0)

6、np方法

s + s
a    2
b    2
c    6
dtype: int32
s
a    1
b    1
c    3
dtype: int32
s[1:] + s[:-1] # nan + !nan = nan,所以差集的value为NaN
a    NaN
b    2.0
c    NaN
dtype: float64
(s[1:] + s[:-1]).dropna()
b    2.0
dtype: float64

DataFrame:可以理解为sql中的table,或者Series构成的字典,可以从以下创建

1、一维数组、列表、Series

2、二维列表

从字典创建

d = {"name":['jack', 'Tom'], "Age":[19, 20]}  # 从字典创建,key就是column
df1 = pd.DataFrame(d)  # 也可以指定index
df1
nameAge
0jack19
1Tom20
df1.Age
0    19
1    20
Name: Age, dtype: int64

从Serise字典创建

d2 = {'name':pd.Series(data=['jack', 'Tom'], index=['a', 'b']),  # index是必须的,如果没有指定就默认为012...
      'Age':pd.Series(data=[19, 16], index=['a', 'b'])}
df2 = pd.DataFrame(d2)
df2
nameAge
ajack19
bTom16

当索引index不一样的时候,会返回union

d3 = {'name':pd.Series(data=['jack', 'Tom'], index=['a', 'b']),
      'Age':pd.Series(data=[19, 16])}
df3 = pd.DataFrame(d3)
df3
nameAge
ajackNaN
bTomNaN
0NaN19.0
1NaN16.0
pd.DataFrame(d2, index=['a', 'd'], columns=['name', 'M/F'])  # 如果指点的index在Series中就直接用,否则新增空数据,columns同理(至少创建一个空的)
nameM/F
ajackNaN
dNaNNaN

从字典构成的列表创建

data = [{'a':1, 'b':2}, {'a':10, 'b':15, 'c':20}]  # key仍然是column,每一个字典都是独立的一行
pd.DataFrame(data)
abc
012NaN
1101520.0
pd.DataFrame(data, columns=['a', 'b'])
ab
012
11015

一般而言字典的key是作为columns,不过调用pd.DataFrame.from_dict(),并且将orient参数设置为’index’可以把key设置为索引

默认情况下,orient等于columns

pd.DataFrame.from_dict({'a':[1,2,3], 'b':[4,5,6]}, orient='index', columns=['first', 'second', 'third'])
firstsecondthird
a123
b456
pd.DataFrame.from_dict({'a':[1,2,3], 'b':[4,5,6]})
ab
014
125
236

columns的增删改查

df4=pd.DataFrame.from_dict({'a':[1,2,3], 'b':[4,5,6]}, orient='index', columns=['first', 'second', 'third'])
df4
firstsecondthird
a123
b456

df4['first']  # 返回Series
a    1
b    4
Name: first, dtype: int64
df4.query('first > 2').query('second < 15')  # 根据条件查
firstsecondthird
b456

df4['third'] = df4['first'] * df4['second']
df4

df[1,2] = 2 # 修改一行2列为2
firstsecondthird
a122
b4520

df4['flag'] = df4['first']>1
df4
firstsecondthirdflag
a122False
b4520True
df4['forth'] = 4
df4
firstsecondthirdflagforth
a122False4
b4520True4
df4.insert(0, 'haha', df4['first'])  # 指定插入的位置
df4
hahafirstsecondthirdflagforth
a1122False4
b44520True4
del df4['haha']
del df4['flag']
df4
firstsecondthirdforth
a1224
b45204

assign用来新增column

df4.assign(ratio=lambda x: x['first'] / x['second'])  # assign只返回原来dataframe的copy,并不会改变原来的数据
firstsecondthirdforthratio
a12240.5
b452040.8
df4
firstsecondthirdforth
a1224
b45204
df4.assign(sum2=df4['first'] + df4['second'])
firstsecondthirdforthsum2
a12243
b452049

del df4['forth']
df4
firstsecondthirdflag
a122False
b4520True
df4.pop('forth')
a    4
b    4
Name: forth, dtype: int64
df4
firstsecondthird
a123
b456
df4.loc['b'].to_numpy()  # 行选
array([4, 5, 6], dtype=int64)
df4.iloc[:2, :]  # 行列切片->矩形范围
firstsecondthird
a123
b456

DataFrame算术运算

df4+1
firstsecondthird
a234
b567
df4.sub(df4['first'], axis=0)  # 减法
firstsecondthird
a012
b012
np.sqrt(df4)  # 面向elements的操作,例如log、sqrt、exp都是可以直接使用的
firstsecondthird
a1.01.4142141.732051
b2.02.2360682.449490

获取表格信息

df4.info()
<class 'pandas.core.frame.DataFrame'>
Index: 2 entries, a to b
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   first   2 non-null      int64
 1   second  2 non-null      int64
 2   third   2 non-null      int64
dtypes: int64(3)
memory usage: 144.0+ bytes
print(df4.to_string())
   first  second  third
a      1       2      3
b      4       5      6

用访问属性的方式访问列

 df6 = pd.DataFrame({'foo1': np.random.randn(5),'foo2': np.random.randn(5)})
df6
foo1foo2
0-0.663151-1.037235
10.492857-0.012955
20.7755530.736301
30.533148-2.451446
4-0.748240-0.465478
df6.foo1
0   -0.663151
1    0.492857
2    0.775553
3    0.533148
4   -0.748240
Name: foo1, dtype: float64

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值