365Tools
发布时间:2024-03-18 16:30:02
我们知道 Pandas 是在 NumPy 的基础构建而来,因此,熟悉 NumPy 可以更加有效的帮助我们使用 Pandas。
import numpy as np
arr = np.array([2, 4, 6, 8, 10, 12])
print(type(arr))
print ("打印新建数组: ",end="")
#使用for循环读取数据
for l in range (0,5):
print (arr[l], end=" ")
输出结果:
虽然 Python 本身没有数组这个说法,不过 Python 提供一个 array 模块,用于创建数字、字符类型的数组,它能够容纳字符型、整型、浮点型等基本类型。示例如下:打印新建数组: 2 4 6 8 10
import array
#注意此处的 'l' 表示有符号int类型
arr = array.array('l', [2, 4, 6, 8, 10, 12])
print(type(arr))
print ("新建数组: ",end="")
for i in range (0,5):
print (arr[i], end=" ")
输出结果:
新建数组: 2 4 6 8 10
import pandas as pd
dict = {'name':["Smith", "William", "Phill", "Parker"],
'age': ["28", "39", "34", "36"]}
info = pd.DataFrame(dict, index = [True, True, False, True])
print(info)
name age
True Smith 28
True William 39
False Phill 34
True Parker 36
然后使用.loc访问索引为 True 的数据。示例如下:
import pandas as pd
dict = {'name':["Smith", "William", "Phill", "Parker"],
'age': ["28", "39", "34", "36"]}
info = pd.DataFrame(dict, index = [True, True, False, True])
#返回所有为 True的数据
print(info.loc[True])
输出结果:
name age
True Smith 28
True William 39
True Parker 36
import numpy as np
arr = np.arange(16)
print("原数组: \n", arr)
arr = np.arange(16).reshape(2, 8)
print("\n变形后数组:\n", arr)
arr = np.arange(16).reshape(8 ,2)
print("\n变形后数组:\n", arr)
输出结果:[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] 变形后数组: [[ 0 1 2 3 4 5 6 7] [ 8 9 10 11 12 13 14 15]] 变形后数组: [[ 0 1] [ 2 3] [ 4 5] [ 6 7] [ 8 9] [10 11] [12 13] [14 15]]
| 比较项 | Pandas | NumPy |
|---|---|---|
| 适应性 | Pandas主要用来处理类表格数据。 | NumPy 主要用来处理数值数据。 |
| 工具 | Pandas提供了Series和DataFrame数据结构。 | NumPy 构建了 ndarray array来容纳数据。 |
| 性能 | Pandas对于处理50万行以上的数据更具优势。 | NumPy 则对于50万以下或者更少的数据,性能更佳。 |
| 内存利用率 | 与 NumPy相比,Pandas会消耗大量的内存。 | NumPy 会消耗较少的内存。 |
| 对象 | Pandas 提供了 DataFrame 2D数据表对象。 | NumPy 则提供了一个多维数组 ndarray 对象 |
DataFrame.to_numpy(dtype=None, copy=False)
参数说明如下:
info = pd.DataFrame({"P": [2, 3], "Q": [4.0, 5.8]})
#给info添加R列
info['R'] = pd.date_range('2020-12-23', periods=2)
print(info)
#将其转化为numpy数组
n=info.to_numpy()
print(n)
print(type(n))
输出结果:
[[2 4.0 Timestamp('2020-12-23 00:00:00')]
[3 5.8 Timestamp('2020-12-24 00:00:00')]]
可以通过 type 查看其类型,输出如下:numpy.ndarray
示例2:
import pandas as pd
#创建DataFrame对象
info = pd.DataFrame([[17, 62, 35],[25, 36, 54],[42, 20, 15],[48, 62, 76]],
columns=['x', 'y', 'z'])
print('DataFrame\n----------\n', info)
#转换DataFrame为数组array
arr = info.to_numpy()
print('\nNumpy Array\n----------\n', arr)
输出结果:
DataFrame
----------
x y z
0 17 62 35
1 25 36 54
2 42 20 15
3 48 62 76
Numpy Array
----------
[[17 62 35]
[25 36 54]
[42 20 15]
[48 62 76]]