Series/DataFrame Selecting/Indexing/Reindexing/多级index

Pandas DataFrame Selecting and Indexing

import numpy as np
import pandas as pd
from pandas import Series, DataFrame

!ls *.csv
  tmdb_5000_movies.csv�

imdb = pd.read_csv('tmdb_5000_movies.csv')

imdb.shape
    (4803, 20)

imdb.head(2)
image.png
imdb.tail(2)  # 查看最后两行数据

imdb.columns  # 查看column name

    Index(['budget', 'genres', 'homepage', 'id', 'keywords', 'original_language',
           'original_title', 'overview', 'popularity', 'production_companies',
           'production_countries', 'release_date', 'revenue', 'runtime',
           'spoken_languages', 'status', 'tagline', 'title', 'vote_average',
           'vote_count'],
          dtype='object')


sub_df = imdb[['budget','original_title','original_language','status']]  #  生成新的dataframe

sub_df.shape

    (4803, 4)

sub_df.iloc[10:12, :]   # index location, 取10到11行,所有列
image.png
sub_df.iloc[:, 1:3].head(2)   # 取1到3列,所有行的前两行
image.png
sub_df.iloc[10:12,2:4]   #  10和11行的2、3列数据
image.png
temp_df = sub_df.iloc[10:20,0:2]

temp_df.loc[15:17,:]   # 取15到16的label, 所有列, 和Index没关系
image.png

Reindexing Series 和 DataFrame

import numpy as np
import pandas as pd
from pandas import Series, DataFrame
  • Series reindex
s1 = Series([1, 2, 3, 4], index=['A', 'B', 'C', 'D'])

s1
    A    1
    B    2
    C    3
    D    4
    dtype: int64

s1.reindex(index=['A','B', 'C', 'D', 'E'])   # shift + tag 显示提示帮助。 reindex生成一个新的Series对象
    A    1.0
    B    2.0
    C    3.0
    D    4.0
    E    NaN
    dtype: float64

s1.reindex(index=['A','B', 'C', 'D', 'E'], fill_value=10)   # 给源series对象不存在的列填充指定值
    A     1
    B     2
    C     3
    D     4
    E    10
    dtype: int64

s2 = Series(['A','B', 'C'], index=[1, 5, 10])

s2
    1     A
    5     B
    10    C
    dtype: object

s2.reindex(index=range(10), method='ffill')  #  frond fill
    0    NaN
    1      A
    2      A
    3      A
    4      A
    5      B
    6      B
    7      B
    8      B
    9      B
    dtype: object
  • reindex dataframe
df1 = DataFrame(np.random.rand(25).reshape([5,5]), index=['A','B', 'D', 'E', 'F'], columns=['c1', 'c2','c3', 'c4', 'c5'])

df1
image.png
df1.reindex(index=['A', 'B', 'C', 'D','E', 'F'], columns=['c1', 'c2','c3', 'c4', 'c5', 'c6'])
image.png
s1
    A    1
    B    2
    C    3
    D    4
    dtype: int64

s1.drop('A')
    B    2
    C    3
    D    4
    dtype: int64

df1.drop('A', axis=0)   ## 删除index:A行

df1.drop('c1', axis=1)  ## 删除column: c1行

多级Series

import numpy as np
import pandas as pd
from pandas import Series, DataFrame

s1 = Series(np.random.randn(6), index=[[1, 1, 1, 2, 2, 2], ['a', 'b' , 'c', 'a', 'b' , 'c']])

s1
    1  a   -1.896724
       b    0.942334
       c   -0.020645
    2  a   -0.520883
       b    1.740697
       c    1.207718
    dtype: float64

s1[1]  # 取出1级 索引为1的值
print(type(s1))   # 返回一个series
    

s1[:, 'a']  # 取出各级的'a'的值. 第一个冒号代指任意的1级。
    1   -1.896724
    2   -0.520883
    dtype: float64
  • 多级Series和DataFrame转换
df1 = s1.unstack()  # 转换series --> dataframe

df1
image.png
df2 = DataFrame([s1[1], s1[2]])   #  多级series的第一级,分别当成dataframe的元素,生成新的dataframe. 和s.unstack生成的一样
  • dataframe转换为多级series
s2 = df1.unstack()   # dataframe的unstack方法生成多级series

s3 = df1.T.unstack() # dataframe的unstack方法生成多级series。 T:会把column[1,2,1,2...]变成1级index,index数据[a, b]变成2级index

s2
    a  1   -1.896724
       2   -0.520883
    b  1    0.942334
       2    1.740697
    c  1   -0.020645
       2    1.207718
    dtype: float64

s3
    1  a   -1.896724
       b    0.942334
       c   -0.020645
    2  a   -0.520883
       b    1.740697
       c    1.207718
    dtype: float64

多级DataFrame

df = DataFrame(np.arange(0,16).reshape([4,4]))

df   # 具有1级column, 1级column的dataframe
image.png
df = DataFrame(np.arange(0,16).reshape([4,4]), index=[['a', 'a', 'b', 'b'], [1,1, 2, 2]])   # 具有多级的index

df
image.png
df = DataFrame(np.arange(0,16).reshape([4,4]), index=[['a', 'a', 'b', 'b'], [1,1, 2, 2]], columns=[['bj', 'bj', 'sh', 'gz'], [8, 9, 8, 8]])   # 具有多级的index,多级column

df
image.png
  • 多级DataFrame访问
df['bj']   # 直接指定column访问

df['bj'][8]   # 指定多级column访问
    a  1     0
       1     4
    b  2     8
       2    12
    Name: 8, dtype: int64

你可能感兴趣的:(Series/DataFrame Selecting/Indexing/Reindexing/多级index)