pandas重新设置列索引_python数据分析包Pandas(一)

pandas重新设置列索引_python数据分析包Pandas(一)_第1张图片

pandas是一个python包,提供快速,灵活和富有表现力的数据结构,旨在使“关系”或“标记”数据的使用既简单又直观。

pandas的两个主要数据结构Series(1维)和DataFrame(2维)能处理金融,统计,社会科学和许多工程领域中的绝大多数典型用例。

梳理参考如下链接:

Package overview​pandas.pydata.org Pandas系列 - Pandas教程™​www.yiibai.com

一、Series对象的创建与索引

系列(Series)是能够保存任何类型的数据(整数,字符串,浮点数,Python对象等)的一维标记数组,轴标签统称为索引。

Pandas系列可以使用以下构造函数创建:

pandas.Series( data, index, dtype, copy)
  • data:可以使各种形式,如:ndarray、list、dictionary、constants
  • index:索引值必须是唯一的,与数据的长度相同。 如果没有索引被传递,默认np.arange(n)。
  • dtype:用于数据类型,如果没有,将推断数据类型。
  • copy:复制数据,默认为false

创建一个空的系列

import pandas as pd
s = pd.Series()
print(s)

输出为:

Series([], dtype: float64)

从数组ndarray创建

import numpy as np
data = np.array(["a","b","c","d","e"])
s = pd.Series(data)#默认索引时
s_1 = pd.Series(data,index = [3,6,2,4,7])#设置索引参数index
print(s,"n",s_1)

输出为:

0    a
1    b
2    c
3    d
4    e
dtype: object 
3    a
6    b
2    c
4    d
7    e
dtype: object

从字典创建一个系列

字典(dict)可以作为输入传递,如果没有指定索引,则按排序顺序取得字典键以构造索引。 如果传递了索引,索引中与标签对应的数据中的值将被拉出。

dictionary = {'one': 2, 'two': 'wangxinli', 'three': 'liyan', 'four': 'ove', 'five': 'L'}
s = pd.Series(dictionary)#为这只index,默认为字典的键值
s_1 = pd.Series(dictionary,index = ["o","p","q","r","s"])#设置的索引和字典的键值均不一样,可见输出是不存在
s_2 = pd.Series(dictionary,index = ['one', 'two', 'three', 'four', 'e'])#设置的索引和字典的键值部分一样
print(s,"n",s_1,"n",s_2)

输出为:

one              2
two      wangxinli
three        liyan
four           ove
five             L
dtype: object 
 o    NaN
p    NaN
q    NaN
r    NaN
s    NaN
dtype: object 
 one              2
two      wangxinli
three        liyan
four           ove
e              NaN
dtype: object

从系列中访问数据

1、系列中的数据可以使用类似于访问ndarray中的数据来访问

dictionary = {'one': 2, 'two': 'wangxinli', 'three': 'liyan', 'four': 'ove', 'five': 'L'}
s = pd.Series(dictionary)#未设置index,默认为字典的键值
print(s[1])#输出第二行的值
print(s[1:3])#输出第二到第三行的值
print(s[:2])#输出第一到第二行的值
print(s[2:])#输出第三到第五行的值
print(s[::-1])#反向输出
print(s[0:-2])#输出第一到倒数第三个的值

输出为:

wangxinli
two      wangxinli
three        liyan
dtype: object
one            2
two    wangxinli
dtype: object
three    liyan
four       ove
five         L
dtype: object
five             L
four           ove
three        liyan
two      wangxinli
one              2
dtype: object
one              2
two      wangxinli
three        liyan
dtype: object

2、使用标签检索数据

dictionary = {'one': 2, 'two': 'wangxinli', 'three': 'liyan', 'four': 'ove', 'five': 'L'}
s = pd.Series(dictionary)#未设置index,默认为字典的键值
print(s["one"])
print(s[["one","five"]])

输出为:

2
one     2
five    L
dtype: object

二、Dataframe对象的创建

dataframe是二维数据结构,即数据以行和列的表格方式排列。

dataframe的功能特点:

  • 潜在的列是不同的类型
  • 大小可变
  • 标记轴(行和列)
  • 可以对行和列执行算术运算

函数pandas.DataFrame

pandas.DataFrame( data, index, columns, dtype, copy)
  • data:数据采取各种形式,如ndarray,series,map,lists,dict,constant和另一个DataFrame均可。
  • index:行标签,如果没有传递索引值,对于行标签,默认索引是np.arrange(n)
  • columns:列标签,如果没有传递索引值,对于列标签,默认索引是np.arrange(n)。
  • dtype:每列的数据类型。
  • copy:默认值为False

创建一个空的dataframe

import pandas as pd
s = pd.DataFrame()
print(s)

输出为:

Empty DataFrame
Columns: []
Index: []

从列表创建dataframe

import pandas as pd
a = [1,2,4,3,"dfg"]
b = [[1,2],["ddf","dfd"],[3,4]]
data_1 = pd.DataFrame(a)
data_2 = pd.DataFrame(b)
print(data_1,"n",data_2)

输出为:

     0
0    1
1    2
2    4
3    3
4  dfg 
      0    1
0    1    2
1  ddf  dfd
2    3    4

从ndarrays 、字典来创建dataframe

import numpy as np
import pandas as pd
a = np.array([[1,2,3,45,5],[1,33,42,2,2]])
dictionary = {'one': 2, 'two': 'wangxinli', 'three': 'liyan', 'four': 'ove', 'five': 'L'}
dictionary_1 = {"one":a[0],"two":a[1]}
data_a = pd.DataFrame(a,columns=["1","3","5","7","9"],index = ["aa","d"])
data_dict = pd.DataFrame(dictionary,index = ["dd"])#index必须添加,不然会报错
data_dict1 = pd.DataFrame(dictionary_1)
print(data_a)
print(data_dict)
print(data_dict1)

输出为:

    1   3   5   7  9
aa  1   2   3  45  5
d   1  33  42   2  2
    one        two  three four five
dd    2  wangxinli  liyan  ove    L
   one  two
0    1    1
1    2   33
2    3   42
3   45    2
4    5    2

从series以及系列字典来创建

a = pd.Series([1,2,3,4])
b = pd.Series([6,4,"dd","vv"])
c = pd.DataFrame([a,b])
d = pd.DataFrame({"one":a,"two":b})
print(c,"n",d)

输出为:

   0  1   2   3
0  1  2   3   4
1  6  4  dd  vv 
    one two
0    1   6
1    2   4
2    3  dd
3    4  vv

三、对dataframe行和列的操作

选择一列、增加列

array = np.arange(20).reshape(4,5)
abc = pd.DataFrame(array)
print(abc[2])
print(abc)
abc[5] = [1,2,3,4]
print(abc)
abc[6] = abc[1]+abc[3]
print(abc)

输出为:

0     2
1     7
2    12
3    17
Name: 2, dtype: int32

    0   1   2   3   4
0   0   1   2   3   4
1   5   6   7   8   9
2  10  11  12  13  14
3  15  16  17  18  19

    0   1   2   3   4  5
0   0   1   2   3   4  1
1   5   6   7   8   9  2
2  10  11  12  13  14  3
3  15  16  17  18  19  4

    0   1   2   3   4  5   6
0   0   1   2   3   4  1   4
1   5   6   7   8   9  2  14
2  10  11  12  13  14  3  24
3  15  16  17  18  19  4  34

列的删除,使用drop函数

drop(self, labels=None, axis=0, index=None, columns=None,
             level=None, inplace=False, errors='raise')

重要参数

  • labels : 选择删除的行和列标签。
  • axis : {0 or 'index', 1 or 'columns'}, 默认0,0表示删除行,1表示删除列。
  • index, columns :直接设置index和columns可以达到设置lables和axis一样的效果。
  • inplace : 是否更改原数据
a = abc.drop(labels=[0,2],axis=0)#删除行标签为0和2的行
print(a)
b = abc.drop(labels=[0,2],axis=1)#删除标签为0和2的列
print(b)
abc.drop(labels=[2,3],axis=1,inplace=True)#删除标签2和3的列,并返回给abc
print(abc)

输出为:

    0   1   2   3   4  5   6
1   5   6   7   8   9  2  14
3  15  16  17  18  19  4  34

    1   3   4  5   6
0   1   3   4  1   4
1   6   8   9  2  14
2  11  13  14  3  24
3  16  18  19  4  34

    0   1   4  5   6
0   0   1   4  1   4
1   5   6   9  2  14
2  10  11  14  3  24
3  15  16  19  4  34

行选择,添加和删除

可以通过将行标签传递给loc()函数来选择行。

print(abc)
print(abc.loc[0,1])
print(abc.loc[[0,1]])
print(abc.loc[[0,1],[0,1]])

输出为:

abc
    0   1   4  5   6
0   0   1   4  1   4
1   5   6   9  2  14
2  10  11  14  3  24
3  15  16  19  4  34
abc.loc[0,1]
1
abc.loc[[0,1]]
   0  1  4  5   6
0  0  1  4  1   4
1  5  6  9  2  14
abc.loc[[0,1],[0,1]]
   0  1
0  0  1
1  5  6

按整数位置选择,可以通过将整数位置传递给iloc()函数来选择行

abc.iloc[1]
abc.iloc[:,[2,3]]

类似于数组切片的操作。

行切片

可以使用:运算符选择多行。

abc[2:3]表示选取第三行。

附加行

使用append()函数将新行添加到DataFrame。

append(self, other, ignore_index=False,verify_integrity=False, sort=None)

重要参数

other:DataFrame、series、dict、list这样的数据结构。

ignore_index:默认值为False,如果为True则不使用index标签。

verify_integrity :默认值为False,如果为True当创建相同的index时会抛出ValueError的异常。

sort:boolean,默认是None,该属性在pandas的0.23.0的版本才存在。

你可能感兴趣的:(pandas重新设置列索引,python,pandas,drop)