pandas中dataFrame的取值和计算操作

dataFrame中的值以矩阵的形式存在,在访问值时需要带上行索引或者列索引。
1、dataFrame简单的取值方法

import pandas as pd

def createDataFrame():
    d = {
        'a':[1,2,3,4,5],
        'b':[6,2,3,6,0],
        'c':[4,2,3,6,7],
        'd':[5,3,2,4,5],
        'e':[6,7,4,5,8]
    }
    df = pd.DataFrame(d)
    #打印出dataFrame
    print(df)

if __name__ == '__main__':
    createDataFrame()

(1)输出前3行数据

print(df.head(3))

打印结果为:

   a  b  c  d  e
0  1  6  4  5  6
1  2  2  2  3  7
2  3  3  3  2  4

(2)输出后2行数据:

  print(df.tail(2))

打印结果为:

   a  b  c  d  e
3  4  6  6  4  5
4  5  0  7  5  8

(3)输出第3行数据:

#loc通过标签来选择数据
print(df.loc[2])#这里的2表示行索引
#iloc通过位置来选择数据
print(df.iloc[2])#这里的2表示行位置
#打印结果
a    3
b    3
c    3
d    2
e    4

(4)输出第2列数据

print(df['b'])
#打印输出
0    6
1    2
2    3
3    6
4    0
#从dataFrame里取出的行或列的类型为Series,其可以看做为一个字典,对Series取值:
x = df.iloc[2]
print(x[2])
#打印输出
3
#可以自荐将Series转换为一个list
x = list(df.iloc[2])

(5)查看行名

   print(df.index)

打印输出:

RangeIndex(start=0, stop=5, step=1)

(6)查看列名

   print(df.columns)

打印输出:

Index(['a', 'b', 'c', 'd', 'e'], dtype='object')

(6)查看所有数据值

   print(df.values)

打印输出:

[[1 6 4 5 6]
 [2 2 2 3 7]
 [3 3 3 2 4]
 [4 6 6 4 5]
 [5 0 7 5 8]]

(7)查看行列数

  print(df.iloc[:,0].size) #行数
  print(df.columns.size) #列数

打印输出:

5
5

2、复杂的dataFrame取值操作(对dataFrame中的数据进行筛选)
创建一个dataFrame例子:

import numpy as np
import pandas as pd


def GroupbyDemo():
    df = pd.DataFrame({'key1': [1, 2, 1, 2, 1],
                       'key2': [10, 20, 30, 40, 50],
                       'data1': np.random.randn(5),
                       'data2': np.random.randn(5)})
    print(df)

if __name__ == '__main__':
    GroupbyDemo()

打印结果:

   key1  key2     data1     data2
0     1    10  0.510140 -0.272037
1     2    20  1.303937 -0.296393
2     1    30  0.984371  0.005988
3     2    40 -1.257891 -1.089489
4     1    50  0.129426 -1.011806

(1)筛选某列中大于某一值得数据:

print(df[df.key1>1])

打印结果为:

   key1  key2     data1     data2
1     2    20  1.006815 -1.191766
3     2    40  0.392499 -0.906492

(2)筛选第一列大于1且第二列大于30的数据

    print(df[(df.key1>1) & (df.key2>30)])

打印结果为:

   key1  key2     data1     data2
3     2    40  0.681879  0.206709

(3)筛选第一列大于1或第二列大于30的数据

   print(df[(df.key1>1) | (df.key2>30)])

打印结果为:

   key1  key2     data1     data2
1     2    20 -2.454197  1.091813
3     2    40  0.481552  0.763660
4     1    50  1.639578  0.740787

3、对dataFrame进行函数操作
(1)转置

print(df.T)

输出结果:

   0  1  2  3  4
a  1  2  3  4  5
b  6  2  3  6  0
c  4  2  3  6  7
d  5  3  2  4  5
e  6  7  4  5  8

猜你喜欢

转载自blog.csdn.net/weixin_34223655/article/details/90862820