anumpy

 

 

import numpy as np
import pandas as pd

def main():
    testRange()
    testReshape()
    testDataFrame()
    testNumpyDemension()
    testRandomRand()

def testRandomRand():
    #np.random.rand(d0,d1,d2……dn)
    #通过本函数可以返回一个或一组服从“0~1”均匀分布的随机样本值。随机样本取值范围是[0,1),不包括1。
    x = np.random.rand(2, 4) #shape为(2, 4)
    print(x)
    x = [[1, 2], [3, 4]]
    y = [2, 3]
    z = np.dot(y, x)
    print(z)
    z = np.dot(x, y)
    print(z)    
        
    # np.random.rand(2, 3)生成一个2*3的二维矩阵,值为随机(0~1)    
    x = np.random.rand(2, 3)
    print(x)
    
    #astype(int)把数据转换成int类型
    x = np.array([2, 3.2, 4.5]).astype(int)
    print(x)  #[2 3 4]

def testDataFrame():
    population = {'city':['Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen', 'Hangzhou', 'Chongqing'],
            'year':[2016, 2017, 2016, 2017, 2016, 2016],
            'population':[2100, 2300, 1000, 700, 500, 500]
            }

    data = pd.DataFrame(population)
    print(data)
    a = data.iloc[:, 1:]
    print(a)
    print("----1111-----")
    a = data.iloc[:, 1:].values #去掉表头
    print(a)
    print("----2222-----")
    a = data.iloc[0]
    print(a)
        
    pdc = pd.DataFrame(population, columns=['year', 'city', 'population'])  # columns参数改变列名
    print(pdc)
    print("----------------")
    
    # loc函数:通过行索引 "Index" 中的具体值来取行数据(如取"Index"为"A"的行)
    # iloc函数:通过行号来取行数据(如取第二行的数据)
    data = pd.DataFrame(np.arange(16).reshape(4, 4), index=list('abcd'), columns=list('ABCD'))
    print(data)    
    
    #####提取行数据###########
    # 取索引为'a'的行
    meta = data.loc['a']
    print(meta)    
    # 取第一行数据,索引为'a'的行就是第一行,所以结果相同
    meta = data.iloc[0]
    print(meta)
    print("------")
    
    ####利用loc、iloc提取列数据######
    # 取'A'列所有行,多取几列格式为 data.loc[:,['A','B']]   
    meta = data.loc[:, ['A']]  
    print(meta)
    # 取第0列所有行,多取几列格式为 data.iloc[:,[0,1]]
    meta = data.iloc[:, [0]]
    print(meta)

    # 利用loc、iloc提取指定行、指定列数据
    # 提取index为'a','b',列名为'A','B'中的数据
    #以下3个结果相同
    meta = data.loc[['a', 'b'], ['A', 'B']]
    print(meta)
    meta = data.iloc[[0, 1], [0, 1]]
    print(meta)
    meta = data.iloc[0:2, 0:2]
    print(meta)    
    
    # 利用loc、iloc提取所有数据
    print("----------333----------")
    meta = data.loc[:, :]  # 取A,B,C,D列的所有行
    meta = data.iloc[:, :]  # 取第0,1,2,3列的所有行
    meta = data.iloc[:, :3] #打印0,1,2列
    print(meta)
    
    # 利用loc函数,根据某个数据来提取数据所在的行
    # 提取data数据(筛选条件: A列中数字为0所在的行数据)
    meta = data.loc[data['A'] == 0]
    print(meta)
    
    print("-----------------------")
    data = pd.DataFrame(np.arange(16).reshape(4, 4))
    print(data)

def testRange():
    for i in range(1, 7, 2):
        print(i)
 
    # np.arange() 它是一个序列,可被当做向量使用。 而且步長可以是浮点数
    for s in np.arange(1, 2, 0.5):
        print(s)


def testReshape():    
    a = np.array([1, 2, 3, 4, 5, 6, 7, 8])
    print(a)
    # reshape()是数组对象中的方法,用于改变数组的形状
    # 形状变化是基于数组元素不能改变的,变成的新形状中所包含的元素个数必须符合原来元素个数。如果数组元素发生变化的时候,就会报错
    b = a.reshape((2, 4))
    print(b)
    
    # reshape函数生成的新数组和原始数组公用一个内存,也就是说,不管是改变新数组还是原始数组的元素,另一个数组也会随之改变
    print("-----reshape()  2 2 2 ")
    c = a.reshape((2, 2, 2))
    print(c)
    print(a)
    c[0][0][0] = 123
    print(a)

def testNumpyDemension():
    #numpy中的ravel()、flatten()、squeeze()都有将多维数组转换为一维数组的功能,区别: 
    #ravel():如果没有必要,不会产生源数据的副本 
    #flatten():返回源数据的副本 
    #squeeze():只能对维数为1的维度降维
    #另外,reshape(-1)也可以“拉平”多维数组
    arr = np.arange(12).reshape(3, 4)
    print(arr);
    arr1 = arr.ravel()
    print(arr1)
    arr2 = arr.flatten()
    print(arr2)
    arr = np.arange(6)
    arr3 = arr.squeeze()
    print(arr3)
    arr4 = arr.reshape(-1)
    print(arr4) 

if __name__ == '__main__':
    main()

1
3
5
1.0
1.5
[1 2 3 4 5 6 7 8]
[[1 2 3 4]
[5 6 7 8]]
-----reshape() 2 2 2
[[[1 2]
[3 4]]

[[5 6]
[7 8]]]
[1 2 3 4 5 6 7 8]
[123 2 3 4 5 6 7 8]
city year population
0 Beijing 2016 2100
1 Shanghai 2017 2300
2 Guangzhou 2016 1000
3 Shenzhen 2017 700
4 Hangzhou 2016 500
5 Chongqing 2016 500
year population
0 2016 2100
1 2017 2300
2 2016 1000
3 2017 700
4 2016 500
5 2016 500
----1111-----
[[2016 2100]
[2017 2300]
[2016 1000]
[2017 700]
[2016 500]
[2016 500]]
----2222-----
city Beijing
year 2016
population 2100
Name: 0, dtype: object
year city population
0 2016 Beijing 2100
1 2017 Shanghai 2300
2 2016 Guangzhou 1000
3 2017 Shenzhen 700
4 2016 Hangzhou 500
5 2016 Chongqing 500
----------------
A B C D
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
d 12 13 14 15
A 0
B 1
C 2
D 3
Name: a, dtype: int32
A 0
B 1
C 2
D 3
Name: a, dtype: int32
------
A
a 0
b 4
c 8
d 12
A
a 0
b 4
c 8
d 12
A B
a 0 1
b 4 5
A B
a 0 1
b 4 5
A B
a 0 1
b 4 5
----------333----------
A B C
a 0 1 2
b 4 5 6
c 8 9 10
d 12 13 14
A B C D
a 0 1 2 3
-----------------------
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
3 12 13 14 15
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[ 0 1 2 3 4 5 6 7 8 9 10 11]
[ 0 1 2 3 4 5 6 7 8 9 10 11]
[0 1 2 3 4 5]
[0 1 2 3 4 5]
[[0.20092984 0.40093063 0.28456675 0.64553236]
[0.72912807 0.36274069 0.30585388 0.28544395]]
[11 16]
[ 8 18]
[[0.54183868 0.33830695 0.25286248]
[0.54406807 0.39408956 0.13452532]]
[2 3 4]

posted @ 2019-01-19 11:35  牧 天  阅读(216)  评论(0)    收藏  举报