【pd】pandas查看数据
df = pd.DataFrame(np.random.randn(5,4),\
index=list("ABCDE"),\
columns=list("MNKP"))
"""
df:
M N K P
A -0.189680 -1.247118 -0.031436 0.509052
B 1.512917 0.726863 1.801891 1.020904
C 0.371600 -0.865672 0.074896 -1.227192
D -0.691088 0.703364 1.755493 0.572169
E -0.084909 0.373502 0.153194 -1.587572
"""
查看前几行、后几行
df.head() # 默认显示前五行
df.tail(3)
显示df的索引(index)或列名(columns)
df.index # Index(['A', 'B', 'C', 'D', 'E'], dtype='object')
df.columns # Index(['M', 'N', 'K', 'P'], dtype='object')
使用 DataFrame.to_numpy() 获取底层数据的 NumPy 表示形式 (不包含索引index和列标签columns)
- NumPy 数组整个数组只能有一种 dtype(数据类型),而 pandas 的 DataFrame 每一列可以有不同的 dtype
- 所以在转换时,pandas 会尝试找到一个统一的 NumPy dtype 来容纳所有列的数据类型。
- 如果列的数据类型差异较大(例如包含字符串和数字),最终可能会统一成 object 类型,并且可能会触发 数据拷贝(copying data)
df.to_numpy()
"""
array([[-0.18968029, -1.24711848, -0.03143575, 0.50905184],
[ 1.51291713, 0.72686321, 1.80189076, 1.02090386],
[ 0.3716002 , -0.86567206, 0.07489649, -1.22719231],
[-0.69108833, 0.70336375, 1.75549259, 0.57216935],
[-0.08490923, 0.37350167, 0.15319386, -1.58757168]])
"""
使用 describe() 快速生成数据的统计摘要
包含:计数(count)、平均值(mean)、标准差(std)、最小值(min)、四分位数(25%、50%、75%)、最大值(max)
df.describe()
"""
M N K P
count 5.000000 5.000000 5.000000 5.000000
mean 0.183768 -0.061812 0.750808 -0.142528
std 0.833508 0.928459 0.940754 1.178301
min -0.691088 -1.247118 -0.031436 -1.587572
25% -0.189680 -0.865672 0.074896 -1.227192
50% -0.084909 0.373502 0.153194 0.509052
75% 0.371600 0.703364 1.755493 0.572169
max 1.512917 0.726863 1.801891 1.020904
"""
转置数据(行列互换)
df.T
"""
A B C D E
M -0.189680 1.512917 0.371600 -0.691088 -0.084909
N -1.247118 0.726863 -0.865672 0.703364 0.373502
K -0.031436 1.801891 0.074896 1.755493 0.153194
P 0.509052 1.020904 -1.227192 0.572169 -1.587572
"""
使用 DataFrame.sort_index() 按索引排序
- 按行排序:axis = 0
- 按列排序:axis = 1
df.sort_index(axis=0) # 按行索引排序
df.sort_index(axis=1) # 按列索引排序
使用 DataFrame.sort_values() 按列中的值进行排序
df.sort_values(by='M')
"""
M N K P
D -0.691088 0.703364 1.755493 0.572169
A -0.189680 -1.247118 -0.031436 0.509052
E -0.084909 0.373502 0.153194 -1.587572
C 0.371600 -0.865672 0.074896 -1.227192
B 1.512917 0.726863 1.801891 1.020904
"""

浙公网安备 33010602011771号