【Pandas】Dataframe

1. 基本概念及创建

1.1 DataFrame简介

  1. Dataframe是一个表格型的数据结构,带有index(行标签)columns(列标签)二维数组
  2. DataFrame的每一列的数据类型相同,相当于一个Series,列名就是Series.name
    import pandas as pd
    import numpy as np
    data = {
        'name': ['Mary', 'Jack'],
        'age': [12, 18],
        'sex': ['女', '男']
    }
    frame = pd.DataFrame(data)
    print(frame)
    print(frame.index)  # 行标签
    print(frame.columns) # 列标签
    print(frame.values)  # 查看值,为二维数组
    
  3. 修改行/列标签:column只是改变已有的列顺序,不能改变成设置的列,但是index可以
    import pandas as pd
    import numpy as np
    data = {
        'name': ['Mary', 'Jack'],
        'age': [12, 18],
    	'sex': ['女', '男']
    }
    # 1. 在创建时修改
    frame = pd.DataFrame(data, index=['a', 'b'])  # 修改行标签,可以重新赋值
    frame = pd.DataFrame(data, columns =['age', 'name'])  # 修改列标签顺序,以及选择哪些列生成数据,也就是新列标签元素个数可以小于原列标签元素个数
    # 2. 创建后修改
    frame.index = ['a', 'b'] # 修改行标签,可以重新赋值
    frame.columns = ['a', 'b'] # 修改行标签,只能修改顺序, 且 新列标签元素个数必须等于原列标签元素个数
    

1.2 创建 Dataframe

(1) 方法一:由数组/list组成的字典

  1. 由数组/list组成的字典 创建Dataframe,columns为字典key,index为默认数字标签

    data1 = {
        'name': ['Mary', 'Jack'],
        'age': [12, 18],
        'sex': ['女', '男']
    }
    frame1 = pd.DataFrame(data1)
    print(frame1)
    

    在这里插入图片描述

  2. 所有的数组/list 长度必须保持一致,否则会报错

    data2 = {
        'one': np.arange(2),     
        'tow': np.arange(10, 12)
    }   
    frame2 = pd.DataFrame(data2)
    print(frame2)  # 报错
    

(2) 方法二:由Series组成的字典

  1. 由Seris组成的字典 创建Dataframe,columns为字典key,index为Series的标签(如果Series没有指定标签,则是默认数字标签)

    data1 = {
    	'one':pd.Series(np.random.rand(2)),
    	'two':pd.Series(np.random.rand(3))
    }  
    df1 = pd.DataFrame(data1)
    print(df1)
    

    在这里插入图片描述

  2. 所有的Series 长度可以不一致

    data2 = {
    	'one':pd.Series(np.arange(2), index=['a', 'b']),
    	'two':pd.Series(np.arange(100, 103), index=['d', 'b', 'c'])
    }
    df2 = pd.DataFrame(data2)
    print(df2)
    

    在这里插入图片描述

(3) 方法三:通过二维数组直接创建

arr = np.arange(20, 30).reshape(2, 5)
df = pd.DataFrame(arr, index=['a', 'b'], columns=['c1', 'c2', 'c3', 'c4', 'c5'])  # column的元素个数必须与二维数组列数相同
print(df)

在这里插入图片描述

(4) 方法四:由字典组成的列表

d = [{'one': 1, 'two': 2}, {'one': 11, 'two': 12, 'three': 13}]  # 列表中的每一个字典,相当于一行
f = pd.DataFrame(d, index=['a', 'b'])
print(f)

在这里插入图片描述

(5) 方法五:由字典组成的字典

data = {
    'name':{'a':'Jack', 'b': 'Mary'},
    'sex':{'a': 18, 'b':19}
}     # 相当于指定行标签
f = pd.DataFrame(data)
print(f)

在这里插入图片描述

2. Dataframe 索引

2.1 选择行与列

(1) 直接访问:只能访问列

df = pd.DataFrame(np.random.rand(12).reshape(3,4)*100,
                   index = ['one','two','three'],
                   columns = ['a','b','c','d'])
df

# 1. 访问一列:
# 返回Series:
print(df.a)  
print(df['a'])
# 返回Dataframe:
print(df[['a']])

# 2. 访问多列
print(df[['a', 'c']]) # 返回Dataframe

(2) df.loc[]函数:按行列名取数

注意:

  1. loc[]切片函数,左边是行切片,表示从哪一行到哪一行;右边是列切片,表示从哪一列到哪一列。
  2. 关于返回的数据类型:
    1. 返回Series类型,在切片位置传入一个列/行名,比如df.loc[: 'column_name']
    2. 返回Dataframe类型,在切片位置传入带列/列名的列表,比如df.loc[:, ['column_name']]
  3. 关于df有无行列标签:
    1. 有行列名时,可通过行列名访问。比如:df.loc['one':'three', ['a']]
    2. 没有行列名时,行名/列名都是从0开始编号,所以此时行名/列名都是数字,可通过数字访问。比如:df.loc[:, 2:3]
  1. 列:

    df = pd.DataFrame(np.random.rand(12).reshape(3,4)*100,
                       index = ['one','two','three'],
                       columns = ['a','b','c','d'])
    df
    
    # 1. 访问一列:
    print(df.loc[:'a'])    # 返回 Series
    print(df.loc[:['a']])  # 返回 Dataframe
    
    # 2. 访问多列
    print(df.loc[:, ['a', 'c']])  # 等价于 print(df.loc['one':'three', ['a', 'c']])  # 选择不相邻的列
    print(df.loc[:, 'a':'c'])  # 当多列相邻时,可用切片简化
    
  2. 行:

    df = pd.DataFrame(np.random.rand(12).reshape(3,4)*100,
                      index = ['one','two','three'],
                      columns = ['a','b','c','d'])
    df
    
    # 1. 访问单行
    df.loc[['one'], :]
    
    # 2. 访问多行
    df.loc[['one', 'three'], :] 
    df.loc['one':'three', :]   # 当多行相邻时,可用切片简化
    

(3) df.iloc[]函数:按下标数字取数

df.iloc[]函数df.loc[]函数 基本一样,只是前者是通过下标访问:
需要注意:df.iloc[]函数获取的列,是左闭右开;df.loc[]函数 获取的列是左闭右闭。

  1. 列:
    df = pd.DataFrame(np.random.rand(12).reshape(3,4)*100,
                       index = ['one','two','three'],
                       columns = ['a','b','c','d'])
    df
    
    # 1. 访问一列:
    df.iloc[:, 1]  # 返回 Series
    df.iloc[:, [1]] # 返回 DataFrame
    
    # 2. 访问多列
    print(df.iloc[:, [0, 2]]) 
    print(df.iloc[:, 0:2])    # 当多列相邻时,可用切片简化
    
  2. 行:只能切片访问
    df = pd.DataFrame(np.random.rand(12).reshape(3,4)*100,
                      index = ['one','two','three'],
                      columns = ['a','b','c','d'])
    df
    
    # 1. 访问单行
    df.iloc[0, :] # 返回 Series
    df.iloc[[0], :] # 返回 Series
    
    # 2. 访问多行
    df.loc[[0, 2], :] 
    df.loc[0:2, :]   # 当多列相邻时,可用切片简化
    

(4) df.ix[]函数

df.loc[][]  左闭右闭行标签/列标签
df.iloc[][)  左闭右开数字索引
df.ix[]数字是[) 行/列标签是[]具有上面的两种功能:数字索引、行/列标签
df = pd.DataFrame(np.random.rand(12).reshape(3,4)*100,
                   index = ['one','two','three'],
                   columns = ['a','b','c','d'])
print(df)
print(df.loc[:, ['a', 'c']])
print(df.iloc[0:2, 1:3])
print(df.ix[0:2, ['a', 'c']])

# 结果:
               a          b          c          d
one    63.666351  61.163233  31.822639  78.653631
two    49.693777  52.420641  42.267130  53.031000
three  44.693220  16.741017  11.834082  97.288596
               a          c
one    63.666351  31.822639
two    49.693777  42.267130
three  44.693220  11.834082
             b          c
one  61.163233  31.822639
two  52.420641  42.267130
             a          c
one  63.666351  31.822639
two  49.693777  42.267130

(5) 布尔型索引

  1. 布尔类型的行列共用

    # 和Series原理相同
    df = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
                       index = ['one','two','three','four'],
                       columns = ['a','b','c','d'])
    print(df)
    print('------')
    print(df>50)
    print('------')
    print(df[df>50]) # 传入每个指的布尔值
    
    # 结果:
                   a          b          c          d
    one    17.212809  74.314714  10.156837  72.622754
    two    88.294727  48.804259  31.103894  20.837973
    three  95.101094  34.875227  78.032575  93.951124
    four   94.727082  43.795659  86.518682  90.068478
    ------
               a      b      c      d
    one    False   True  False   True
    two     True  False  False  False
    three   True  False   True   True
    four    True  False   True   True
    ------
                   a          b          c          d
    one          NaN  74.314714        NaN  72.622754
    two    88.294727        NaN        NaN        NaN
    three  95.101094        NaN  78.032575  93.951124
    four   94.727082        NaN  86.518682  90.068478
    
  2. 布尔类型的行与列

    df = pd.DataFrame({
        'key1':np.arange(5),
        'key2':np.arange(5, 10),
    }, index=list('abcde'))
    print(df)
    print('------')
    s = pd.Series({'a':True, 'b':False, 'c':True, 'd':False, 'e':False})
    print(df[s])
    
    s2 = pd.Series({'key1':True, 'key2':False})
    print(s2)
    print(df.columns[s2])
    
    # 结果:
       key1  key2
    a     0     5
    b     1     6
    c     2     7
    d     3     8
    e     4     9
    ------
       key1  key2
    a     0     5
    c     2     7
    key1     True
    key2    False
    dtype: bool
    Index(['key1'], dtype='object')
    

(6) 多重索引

# 多重索引:比如同时索引行和列
# 先选择列再选择行 —— 相当于对于一个数据,先筛选字段,再选择数据量
df = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
                   index = ['one','two','three','four'],
                   columns = ['a','b','c','d'])
print(df)
print('------')

print(df['a'].loc[['one','three']])   # 选择a列的one,three行

# 结果:
               a          b          c          d
one    73.315488  34.853760  22.059922  44.274220
two     7.484602  22.595569  32.362358  26.621247
three  21.273322  16.585421  48.346943  49.811086
four   79.518511   4.416195  29.054869  76.588620
------
one      73.315488
three    21.273322
Name: a, dtype: float64

— 判断返回类型是Series还是Dataframe小技巧

  • df后面有几层[]括号,一层就是Series,二层就是Dataframe

3. 基本技巧

3.1 查看收尾n行、转置

df = pd.DataFrame(np.random.rand(5, 2),
                 columns=['a', 'b'])
print(df)

# .head()查看头部数据,不带参数默认是5行
print(df.head(2))  

# .tail()查看尾部数据,不带参数默认是5行
print(df.tail(2))  

# 转置
print(df.T)
# 结果:
          a         b
0  0.178140  0.626120
1  0.875550  0.106871
2  0.051926  0.959511
3  0.770076  0.005052
4  0.846975  0.292112
         a         b
0  0.17814  0.626120
1  0.87555  0.106871
          a         b
3  0.770076  0.005052
4  0.846975  0.292112
         0         1         2         3         4
a  0.17814  0.875550  0.051926  0.770076  0.846975
b  0.62612  0.106871  0.959511  0.005052  0.292112

3.2 添加与修改

  1. 先获取Series,再用loc[]获取元素,最后直接修改元素即可
  2. 直接添加一列或者一行
df = pd.DataFrame(np.arange(20).reshape(4, 5),
                 columns=list('abcde'))
print(df)

# 修改元素值:
df['a'].loc[0] = 100
print(df)

# 添加元素值
print('添加-------')
df['f'] = 300
print(df)
# 结果:
    a   b   c   d   e
0   0   1   2   3   4
1   5   6   7   8   9
2  10  11  12  13  14
3  15  16  17  18  19
     a   b   c   d   e
0  100   1   2   3   4
1    5   6   7   8   9
2   10  11  12  13  14
3   15  16  17  18  19
添加-------
     a   b   c   d   e    f
0  100   1   2   3   4  300
1    5   6   7   8   9  300
2   10  11  12  13  14  300
3   15  16  17  18  19  300

3.3 删除

f = pd.DataFrame(np.arange(20).reshape(4, 5),
                 columns=list('abcde'))
print(df)

# drop()语句删除列, 需要指定 axis = 1
print(df.drop(['e'], axis=1))  # inplace=False → 删除后生成新的数据,不改变原数据

# drop()删除行,不需要指定 axis = 1
print(df.drop(0)) # inplace=False → 删除后生成新的数据,不改变原数据

在这里插入图片描述

3.4 对齐

df1 = pd.DataFrame(np.random.randn(10, 4), columns=['A', 'B', 'C', 'D'])
df2 = pd.DataFrame(np.random.randn(7, 3), columns=['A', 'B', 'C'])
print(df1 + df2)
# DataFrame对象之间的数据自动按照列和索引(行标签)对齐
# 结果:
          A         B         C   D
0 -0.286501  0.101564  0.934023 NaN
1  0.002405 -0.674116 -1.688925 NaN
2 -1.374691  0.188597  0.161464 NaN
3 -1.209863 -1.844409 -0.591461 NaN
4 -2.605153 -1.473555  1.891570 NaN
5  2.782283  1.193310 -1.139518 NaN
6  1.494297  1.553604  3.075171 NaN
7       NaN       NaN       NaN NaN
8       NaN       NaN       NaN NaN
9       NaN       NaN       NaN NaN

3.5 排序1 - 按值排序 .sort_values

# 同样适用于Series
df = pd.DataFrame(np.random.rand(4,4)*100,
                 columns=['a', 'b', 'c', 'd'])
print(df)
# 单列排序
print(df.sort_values(['a'], ascending=False)) # ascending参数:设置升序降序,默认升序
print('多列排序------')
# 多列排序,按列顺序排序
print(df.sort_values(['a', 'd'], , ascending=False)) # 先按a排序,如果a的值相同,则按d的值排序
# 结果:
           a          b          c          d
0  36.300085  90.999611  87.883077  39.251081
1  16.769310  99.653961  66.176705  10.763438
2  69.271539  94.620625  16.709941  95.833152
3  31.870412  92.897303  45.783337  43.051783
           a          b          c          d
2  69.271539  94.620625  16.709941  95.833152
0  36.300085  90.999611  87.883077  39.251081
3  31.870412  92.897303  45.783337  43.051783
1  16.769310  99.653961  66.176705  10.763438
多列排序------
           a          b          c          d
1  16.769310  99.653961  66.176705  10.763438
3  31.870412  92.897303  45.783337  43.051783
0  36.300085  90.999611  87.883077  39.251081
2  69.271539  94.620625  16.709941  95.833152

3.6 排序2 - 索引排序 .sort_index

# 与.sort_values类似
df1 = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
                  index = [5,4,3,2],
                   columns = ['a','b','c','d'])
df2 = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
                  index = ['h','s','x','g'],
                   columns = ['a','b','c','d'])
# 按照index排序
# 默认 ascending=True, inplace=False
print(df1)
print(df1.sort_index())
print(df2)
print(df2.sort_index())
# 结果:
           a          b          c          d
5  10.912363  66.069285  75.108926  50.976926
4  10.068745  89.445559  68.636782  56.758989
3   5.706953  17.755349  10.428633  31.123841
2  87.497426  76.308941  85.110218  97.168951
           a          b          c          d
2  87.497426  76.308941  85.110218  97.168951
3   5.706953  17.755349  10.428633  31.123841
4  10.068745  89.445559  68.636782  56.758989
5  10.912363  66.069285  75.108926  50.976926
           a          b          c          d
h  70.385483  10.462891  83.496788  82.744301
s  12.271862  25.484720  18.975885  25.769192
x  83.282964  58.578331   5.013539  12.543449
g  62.352057  18.190354  71.342096  28.424552
           a          b          c          d
g  62.352057  18.190354  71.342096  28.424552
h  70.385483  10.462891  83.496788  82.744301
s  12.271862  25.484720  18.975885  25.769192
x  83.282964  58.578331   5.013539  12.543449

4. 数值计算和统计基础

1.基本参数:axis、skipna
import numpy as np
import pandas as pd

df = pd.DataFrame({'key1':[4,5,3,np.nan,2], # 不是基本类型的元素会记为NaN
                 'key2':[1,2,np.nan,4,5],   
                 'key3':[1,2,3,'j','k']},   # 不一样的类型,会向大的类型转换
                 index = ['a','b','c','d','e'])
print(df)

m = df.mean() # 求每列的平均值
print(m, type(m)) # 对每一列求平均值(非数字的不计算在内,比如字符串),为NaN的当作不存在(不做加数也不做除数),然后将结果和列名组成Series
# 单独统计某一列
print('单独统计一列:', df['key2'].mean())

# axis参数:默认为0,以列来计算,axis=1,以行来计算,这里就按照行来汇总了
print(df.mean(axis=1))  # 也可以先转置,用mean(),再转置
# skipna参数:是否忽略NaN,默认True,如False,有NaN的列统计结果仍未NaN
print(df.mean(skipna=False))

# 结果:
   key1  key2 key3
a   4.0   1.0    1
b   5.0   2.0    2
c   3.0   NaN    3
d   NaN   4.0    j
e   2.0   5.0    k
key1    3.5
key2    3.0
dtype: float64 <class 'pandas.core.series.Series'>
单独统计一列: 3.0
a    2.5
b    3.5
c    3.0
d    4.0
e    3.5
dtype: float64
key1   NaN
key2   NaN
dtype: float64
2.主要数学计算方法,可用于Series和DataFrame(1)
df = pd.DataFrame({'key1':np.arange(10),
                  'key2':np.random.rand(10)*10})
print(df)
print('-----')

print(df.count(),'→ count统计非Na值的数量\n')
print(df.min(),'→ min统计最小值\n',df['key2'].max(),'→ max统计最大值\n')
print(df.quantile(q=0.75),'→ quantile统计分位数,参数q确定位置\n')
print(df.sum(),'→ sum求和\n')
print(df.mean(),'→ mean求平均值\n')
print(df.median(),'→ median求算数中位数,50%分位数\n')
print(df.std(),'\n',df.var(),'→ std,var分别求标准差,方差\n')
print(df.skew(),'→ skew样本的偏度\n')
print(df.kurt(),'→ kurt样本的峰度\n')
# 以上都可以用axis、skipna参数调整

# 结果:
   key1      key2
0     0  0.221860
1     1  5.431973
2     2  2.416677
3     3  4.770743
4     4  8.675935
5     5  7.304455
6     6  9.634564
7     7  8.857369
8     8  5.373542
9     9  3.293329
-----
key1    10
key2    10
dtype: int64 → count统计非Na值的数量

key1    0.00000
key2    0.22186
dtype: float64 → min统计最小值
 9.634563862337554 → max统计最大值

key1    6.750000
key2    8.333065
Name: 0.75, dtype: float64 → quantile统计分位数,参数q确定位置

key1    45.000000
key2    55.980447
dtype: float64 → sum求和

key1    4.500000
key2    5.598045
dtype: float64 → mean求平均值

key1    4.500000
key2    5.402758
dtype: float64 → median求算数中位数,50%分位数

key1    3.027650
key2    3.062325
dtype: float64 
 key1    9.166667
key2    9.377834
dtype: float64 → std,var分别求标准差,方差

key1    0.000000
key2   -0.318676
dtype: float64 → skew样本的偏度

key1   -1.200000
key2   -0.757927
dtype: float64 → kurt样本的峰度
3.主要数学计算方法,可用于Series和DataFrame(2)
df = pd.DataFrame({
    'key1': np.arange(5),
    'key2': np.arange(10, 15)
})
print(df)
print(df.cumsum())
# 样本值的累计和,依次向上累计
print('---样本值的累计和')
df['key_s1'] = df['key1'].cumsum()
df['key_s2'] = df['key2'].cumsum()
print(df)
print('----样本值的累计积')
df['key_s3'] = df['key1'].cumprod()
df['key_s4'] = df['key2'].cumprod()
print(df)

# 结果:
   key1  key2
0     0    10
1     1    11
2     2    12
3     3    13
4     4    14
   key1  key2
0     0    10
1     1    21
2     3    33
3     6    46
4    10    60
---样本值的累计和
   key1  key2  key_s1  key_s2
0     0    10       0      10
1     1    11       1      21
2     2    12       3      33
3     3    13       6      46
4     4    14      10      60
----样本值的累计积
   key1  key2  key_s1  key_s2  key_s3  key_s4
0     0    10       0      10       0      10
1     1    11       1      21       0     110
2     2    12       3      33       0    1320
3     3    13       6      46       0   17160
4     4    14      10      60       0  240240
4.唯一值:.unique()
s = pd.Series(list('abacgg'))
sq = s.unique()  # 去掉后面重复的value
print(s)
print(sq, type(sq))  # 得到一个唯一值数组

# 结果:
0    a
1    b
2    a
3    c
4    g
5    g
dtype: object
['a' 'b' 'c' 'g'] <class 'numpy.ndarray'>

注意:unique()方法只有Series有,DataFrame没有

5.值计数:.value_counts()
s = pd.Series(list('abacgg'))
sv = s.value_counts(sort=False) # 默认sout为True也就是默认会将index排序
print(sv)

# 结果:
a    2
c    1
g    2
b    1
dtype: int64

注意:value_counts()也是只能用于Series

6.成员资格:.isin()
# 就是元素是否在Series或者DataFrame中

s = pd.Series(np.arange(5))
df = pd.DataFrame({
    'key1': ['ab', 'a', 'cd'],
    'key2': ['b', 'bc', 'cd']
})
print(s)
print(df)
print(s.isin([4]))
print(df.isin(['c', 'a']))

# 结果:
0    0
1    1
2    2
3    3
4    4
dtype: int32
  key1 key2
0   ab    b
1    a   bc
2   cd   cd
0    False
1    False
2    False
3    False
4     True
dtype: bool
    key1   key2
0  False  False
1   True  False
2  False  False

5. 文本数据

主要内容:Pandas针对字符串配备的一套方法,使其易于对数组的每个元素进行操作

1.通过str访问,且自动排除丢失/ NA值
# 通过str访问,且自动排除丢失/ NA值
# 牢记: str 是对所有的元素进行操作

s = pd.Series(['A','b','C','bbhello','123',np.nan,'hj'])
df = pd.DataFrame({'key1':list('abcdef'),
                  'key2':['hee','fv','w','hija','123',np.nan]})
print(s)
print(df)
print('-----')

print(s.str.count('b'))
print(df['key2'].str.upper())
print('-----')
# 直接通过.str调用字符串方法
# 可以对Series、Dataframe使用
# 自动过滤NaN值

df.columns = df.columns.str.upper()
print(df)
# df.columns是一个Index对象,也可使用.str

# 结果:
0          A
1          b
2          C
3    bbhello
4        123
5        NaN
6         hj
dtype: object
  key1  key2
0    a   hee
1    b    fv
2    c     w
3    d  hija
4    e   123
5    f   NaN
-----
0    0.0
1    1.0
2    0.0
3    2.0
4    0.0
5    NaN
6    0.0
dtype: float64
0     HEE
1      FV
2       W
3    HIJA
4     123
5     NaN
Name: key2, dtype: object
-----
  KEY1  KEY2
0    a   hee
1    b    fv
2    c     w
3    d  hija
4    e   123
5    f   NaN

注意:str只是Series有的属性,对于DataFrame没有

2.字符串常用方法(1) - lower,upper,len,startswith,endswith
s = pd.Series(['A','b','bbhello','123',np.nan])

print(s.str.lower(),'→ lower小写\n')
print(s.str.upper(),'→ upper大写\n')
print(s.str.len(),'→ len字符长度\n')
print(s.str.startswith('b'),'→ 判断起始是否为a\n')
print(s.str.endswith('3'),'→ 判断结束是否为3\n')

# 结果:
0          a
1          b
2    bbhello
3        123
4        NaN
dtype: object → lower小写

0          A
1          B
2    BBHELLO
3        123
4        NaN
dtype: object → upper大写

0    1.0
1    1.0
2    7.0
3    3.0
4    NaN
dtype: float64 → len字符长度

0    False
1     True
2     True
3    False
4      NaN
dtype: object → 判断起始是否为a

0    False
1    False
2    False
3     True
4      NaN
dtype: object → 判断结束是否为3
3.字符串常用方法(2) - strip
s = pd.Series([' jack', 'jill ', ' jesse ', 'frank'])
df = pd.DataFrame(np.random.randn(3, 2), columns=[' Column A ', ' Column B '],
                  index=range(3))
print(s)
print(df)
print('-----')

print(s.str.strip())  # 去除字符串中的空格
print(s.str.lstrip())  # 去除字符串中的左空格
print(s.str.rstrip())  # 去除字符串中的右空格

df.columns = df.columns.str.strip()
print(df)
# 这里去掉了columns的前后空格,但没有去掉中间空格
# 结果:
0       jack
1      jill 
2     jesse 
3      frank
dtype: object
    Column A    Column B 
0   -0.491619   -0.219010
1   -0.217828    0.629777
2   -1.072765    1.182866
-----
0     jack
1     jill
2    jesse
3    frank
dtype: object
0      jack
1     jill 
2    jesse 
3     frank
dtype: object
0      jack
1      jill
2     jesse
3     frank
dtype: object
   Column A  Column B
0 -0.491619 -0.219010
1 -0.217828  0.629777
2 -1.072765  1.182866
4.字符串常用方法(3) - replace
df = pd.DataFrame(np.random.randn(3, 2), columns=[' Column A ', ' Column B '],
                  index=range(3))
df.columns = df.columns.str.replace(' ','-')
print(df)
# 替换

df.columns = df.columns.str.replace('-','hehe',n=1)  # n:替换个数
print(df)

#  结果:
   -Column-A-  -Column-B-
0   -0.008104    0.257773
1   -0.623774    0.721328
2   -0.060201   -0.493679
   heheColumn-A-  heheColumn-B-
0      -0.008104       0.257773
1      -0.623774       0.721328
2      -0.060201      -0.493679
5.字符串常用方法(4) - split、rsplit
s = pd.Series(['a,b,c','1,2,3',['a,,,c'],np.nan])
# 类似字符串的split
print(s.str.split(','))
print('-----')

# 直接索引得到一个list
print(s.str.split(',')[0])
print('-----')

print(s.str.split(',').str[0]) # str[0]可以用get(0)代替
print(s.str.split(',').str.get(1))
print('-----')

# 可以使用expand可以轻松扩展此操作以返回DataFrame
# n参数限制分割数
# rsplit类似于split,反向工作,即从字符串的末尾到字符串的开头
print(s.str.split(',', expand=True))
print(s.str.split(',', expand=True, n = 1))
print(s.str.rsplit(',', expand=True, n = 1))

# 结果:
0    [a, b, c]
1    [1, 2, 3]
2          NaN
3          NaN
dtype: object
-----
['a', 'b', 'c']
-----
0      a
1      1
2    NaN
3    NaN
dtype: object
0      b
1      2
2    NaN
3    NaN
dtype: object
-----
     0    1    2
0    a    b    c
1    1    2    3
2  NaN  NaN  NaN
3  NaN  NaN  NaN
     0    1
0    a  b,c
1    1  2,3
2  NaN  NaN
3  NaN  NaN
     0    1
0  a,b    c
1  1,2    3
2  NaN  NaN
3  NaN  NaN
6.字符串索引
s = pd.Series(['A','b','C','bbhello','123',np.nan,'hj'])
df = pd.DataFrame({'key1':list('abcdef'),
                  'key2':['hee','fv','w','hija','123',np.nan]})

print(s.str[0])  # 取第一个字符串
print(s.str[:2])  # 取前两个字符串
print(df['key2'].str[0]) 
# str之后和字符串本身索引方式相同

# 结果:
0      A
1      b
2      C
3      b
4      1
5    NaN
6      h
dtype: object
0      A
1      b
2      C
3     bb
4     12
5    NaN
6     hj
dtype: object
0      h
1      f
2      w
3      h
4      1
5    NaN
Name: key2, dtype: object
7.一个值得学习的小例子
df = pd.DataFrame({'name':['jack','tom','Marry','zack','heheda'],
                  'gender':['M ','M','   F','  M ','  F'],
                  'score':['90-92-89','89-78-88','90-92-95','78-88-76','60-60-67']})
df['name'] = df['name'].str.capitalize()
df['gender'] = df['gender'].str.strip()
df['math'] = df['score'].str.split('-', expand=True)[0]   # 这个值得学习
print(df)

# 结果:
     name gender     score math
0    Jack      M  90-92-89   90
1     Tom      M  89-78-88   89
2   Marry      F  90-92-95   90
3    Zack      M  78-88-76   78
4  Heheda      F  60-60-67   60