pandas

1. pd.Series

1.1 原数据为列表 [x1,x2]

在用series时,当初始数据为列表(r=[1,2])时,我们当使用 copy=False 时,因为原始数据为列表,所以改后的数据不会引起之前的数据变化;

  • 代码
r = [1, 2]
print('before_r\n', r) #[1,2]
ser = pd.Series(data=r, copy=False) # pd.series[1,2]
print('before_ser\n', ser)
ser.iloc[0] = 99
print('after_r\n', r)  # 此时 r 不会随着 series 的变化而变化
print('after_ser\n', ser) # pd.series[99,2]
print('*' * 100)
  • 结果
****************************************************************************************************
before_r
 [1, 2]
before_ser
 0    1
1    2
dtype: int64
after_r
 [1, 2]
after_ser
 0    99
1     2
dtype: int64

1.2 原数据为 np.array([1,2])

在用series时,当初始数据为np.array([1,2])时,我们当使用 copy=False 时,因为原始数据为numpy.array,所以改后的数据会引起之前的数据变化;

  • 代码
r = np.array([1, 2])
print('before_r\n', r)
ser = pd.Series(data=r, copy=False)
print('before_ser\n', ser)
ser.iloc[0] = 99
print('after_r\n', r)
print('after_ser\n', ser)
  • 结果
before_r
 [1 2]
before_ser
 0    1
1    2
dtype: int32
after_r
 [99  2]
after_ser
 0    99
1     2
dtype: int32

1.3 小结

在这里插入图片描述

2. pd.date_range

2.1 说明

返回一个固定频率的DatetimeIndex

2.2 代码

import pandas as pd
print('*'*100)
# date_range 配合 start -> end ;开始日期和结束日期
date_start_end = pd.date_range(start='1-1-2021',end='12-31-2021')
print('date_start_end\n',date_start_end)

print('*'*100)
# date_range 配合时间长短 period,默认是以天数来计数的
date_period = pd.date_range('1-1-2021',periods=8)
print('date_period\n',date_period)
print('*'*100)

# date_range 配合时间长短periods ,就将整个时间段分成了 period 份
date_start_end_period = pd.date_range(start='1-1-2021',end='2-1-2021',periods=5)
print('date_start_end_period\n',date_start_end_period)
print('*'*100)
# date_range 配合freq来确定是以月为单位就用 freq = 'M';
date_start_period_freq_M = pd.date_range(start='1-1-2021',periods=5,freq='M')
print('date_start_period_freq\n',date_start_period_freq_M)

print('*'*100)
# date_range 配合freq来确定是以月为单位就用 freq = '3M',表示以3个月为单位;
date_start_period_freq_3M = pd.date_range(start='1-1-2021',periods=5,freq='3M')
print('date_start_period_freq_3M\n',date_start_period_freq_3M)

2.3 结果

****************************************************************************************************
date_start_end
 DatetimeIndex(['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04',
               '2021-01-05', '2021-01-06', '2021-01-07', '2021-01-08',
               '2021-01-09', '2021-01-10',
               ...
               '2021-12-22', '2021-12-23', '2021-12-24', '2021-12-25',
               '2021-12-26', '2021-12-27', '2021-12-28', '2021-12-29',
               '2021-12-30', '2021-12-31'],
              dtype='datetime64[ns]', length=365, freq='D')
****************************************************************************************************
date_period
 DatetimeIndex(['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04',
               '2021-01-05', '2021-01-06', '2021-01-07', '2021-01-08'],
              dtype='datetime64[ns]', freq='D')
****************************************************************************************************
date_start_end_period
 DatetimeIndex(['2021-01-01 00:00:00', '2021-01-08 18:00:00',
               '2021-01-16 12:00:00', '2021-01-24 06:00:00',
               '2021-02-01 00:00:00'],
              dtype='datetime64[ns]', freq=None)
****************************************************************************************************
date_start_period_freq
 DatetimeIndex(['2021-01-31', '2021-02-28', '2021-03-31', '2021-04-30',
               '2021-05-31'],
              dtype='datetime64[ns]', freq='M')
****************************************************************************************************
date_start_period_freq_3M
 DatetimeIndex(['2021-01-31', '2021-04-30', '2021-07-31', '2021-10-31',
               '2022-01-31'],
              dtype='datetime64[ns]', freq='3M')

3. pd.DataFrame

3.1 说明

DataFrame 是一个 pandas 中常用的单位,主要具有如下特征

  • 二维:跟Excel表格一样,由行和列组成
  • 大小可变:指的是我们可以根据需要来改变 DataFrame 的大小
  • 可能异构:不太明白

3.2 创建方式

  • dictionary 字典形式
  • numpy.array 方式

3.3 代码

print('*'*100)
# 1.通过 dictionary 来创建 DataFrame
d = {'col1':[1,2],'col2':[4,5]}
df_d = pd.DataFrame(d)
print('df_d:\n',df_d)
print('*'*100)
# 2. 通过 numpy.array 来创建 DataFrame
numpy_array = np.array([[1,2,3],[4,5,6],[7,8,9]])
df_array = pd.DataFrame(data=numpy_array,columns=['a','b','c'])
print('df_array:\n',df_array)
print('*'*100)

3.4 结果

****************************************************************************************************
df_d:
    col1  col2
0     1     4
1     2     5
****************************************************************************************************
df_array:
    a  b  c
0  1  2  3
1  4  5  6
2  7  8  9
****************************************************************************************************

4. pd.iloc&pd.loc

4.1 区别

  • pandas.DataFrame.loc:是按照真实的标签 label 进行检索行的
  • pandas.DataFrame.iloc:是按照索引的值进行检索的

4.2 代码

import pandas as pd
mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]
df = pd.DataFrame(mydict)
print('df=\n',df)
print('*'*100)
# iloc 来源于 index location :即按照序列值进行索引:
# df.iloc[1:]:表示的是从第 1 行到最后。
print('df[1:]=\n',df.iloc[1:])
print('*'*100)
# df.iloc[1,2] :表示的是第 1 行,第 2 列的元素;即:df[1,2]=300
print('df[1,2]=',df.iloc[1,2])
print('*'*100)
# df.loc 是根据真实 label 进行索引的。
mydict_loc = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]
df_loc = pd.DataFrame(mydict_loc,index=['m','n','k'])
print('df_loc\n',df_loc)
print('*'*100)
print('df_loc.loc[label_k]=\n',df_loc.loc['k'])

4.3 结果

df=
       a     b     c     d
0     1     2     3     4
1   100   200   300   400
2  1000  2000  3000  4000
****************************************************************************************************
df[1:]=
       a     b     c     d
1   100   200   300   400
2  1000  2000  3000  4000
****************************************************************************************************
df[1,2]= 300
****************************************************************************************************
df_loc
       a     b     c     d
m     1     2     3     4
n   100   200   300   400
k  1000  2000  3000  4000
****************************************************************************************************
df_loc.loc[label_k]=
 a    1000
b    2000
c    3000
d    4000
Name: k, dtype: int64

5. pd.isnull

5.1 说明

如果矩阵中的值为NaN,那么返回True,否侧为 False

5.2 代码

mydict_loc = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]
df_loc = pd.DataFrame(mydict_loc,index=['m','n','k'])
print('df_loc\n',df_loc)
print('*'*100)
print('df_loc.loc[label_k]=\n',df_loc.loc['k'])
print('*'*100)
# 将第1行2列的值变成 NaN
df_loc.iloc[1,2] = np.nan
print(df_loc)
print('*'*100)
print('求得矩阵中缺省的值,如果则为False-isnull:\n',df_loc.isnull())
print('*'*100)
print('求得矩阵中缺省的值,如果则为False-isna:\n',df_loc.isna())

5.3 结果

****************************************************************************************************
      a     b       c     d
m     1     2     3.0     4
n   100   200     NaN   400
k  1000  2000  3000.0  4000
****************************************************************************************************
求得矩阵中缺省的值,如果则为False-isnull:
        a      b      c      d
m  False  False  False  False
n  False  False   True  False
k  False  False  False  False
****************************************************************************************************
求得矩阵中缺省的值,如果则为False-isna:
        a      b      c      d
m  False  False  False  False
n  False  False   True  False
k  False  False  False  False

6. pd.fillna

6.1 说明

通过给定dataframe.fillna(i) 可以将,dataframe里面的所有NaN用指定的 i 填充

6.2 代码

mydict_loc = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]
df_loc = pd.DataFrame(mydict_loc,index=['m','n','k'])
print('df_loc\n',df_loc)
print('*'*100)
print('df_loc.loc[label_k]=\n',df_loc.loc['k'])
print('*'*100)
# 将第1行2列的值变成 NaN
df_loc.iloc[1,2] = np.nan
print(df_loc)
print('*'*100)
print('求得矩阵中缺省的值,如果则为False-isnull:\n',df_loc.isnull())
print('*'*100)
print('求得矩阵中缺省的值,如果则为False-isna:\n',df_loc.isna())
print('*'*100)
df_loc=df_loc.fillna(888)
print('fillna(888)\n',df_loc)

6.3 结果

****************************************************************************************************
      a     b       c     d
m     1     2     3.0     4
n   100   200     NaN   400
k  1000  2000  3000.0  4000
****************************************************************************************************
求得矩阵中缺省的值,如果则为False-isnull:
        a      b      c      d
m  False  False  False  False
n  False  False   True  False
k  False  False  False  False
****************************************************************************************************
求得矩阵中缺省的值,如果则为False-isna:
        a      b      c      d
m  False  False  False  False
n  False  False   True  False
k  False  False  False  False
****************************************************************************************************
fillna(888)
       a     b       c     d
m     1     2     3.0     4
n   100   200   888.0   400
k  1000  2000  3000.0  4000

7. pd.concat

按 行 (index) 合并矩阵数据

7.1 ignore_index

ignore_index=True; 忽略行表,重新进行标注;

7.2 代码

s1 = pd.Series(['a','b'])
s2 = pd.Series(['c','d'])
pd_concat = pd.concat([s1,s2])
print('pd_concat:行坐标不变\n',pd_concat)
print('*'*50)
pd_concat_ignore_idex = pd.concat([s1,s2],ignore_index=True)
print('pd_concat_ignore_idex:行坐标重新排序:\n',pd_concat_ignore_idex)

7.3 结果

pd_concat:行坐标不变
 0    a
1    b
0    c
1    d
dtype: object
**************************************************
pd_concat_ignore_idex:行坐标重新排序:
 0    a
1    b
2    c
3    d
dtype: object

8.join

8.1 说明

按列来合并矩阵,行数不够用 NaN 来填充

8.2 代码

import pandas as pd
df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'],
                   'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})
other = pd.DataFrame({'key': ['K0', 'K1', 'K2'],
                      'B': ['B0', 'B1', 'B2']})
print('df:\n',df)
print('*'*50)
print('other\n',other)
print('*'*50)
# 合并两个矩阵,如果两个矩阵行数不一样,就用NaN填充
join_together = df.join(other,lsuffix='_caller',rsuffix='_other')
print('join_together:\n',join_together)
print('*'*50)

8.3 结果

df:
   key   A
0  K0  A0
1  K1  A1
2  K2  A2
3  K3  A3
4  K4  A4
5  K5  A5
**************************************************
other
   key   B
0  K0  B0
1  K1  B1
2  K2  B2
**************************************************
join_together:
   key_caller   A key_other    B
0         K0  A0        K0   B0
1         K1  A1        K1   B1
2         K2  A2        K2   B2
3         K3  A3       NaN  NaN
4         K4  A4       NaN  NaN
5         K5  A5       NaN  NaN
**************************************************

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值