1.使用DataFrame建表的三種方式
import numpy as np import pandas as pd test_1 = pd.DataFrame(np.random.rand(4, 4), index=list('ABCD'), columns=list('1234')) # 產生隨機數,index行,columns列 test_2 = pd.DataFrame([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7]], index=list('1234'), columns=list('ABCD')) # 自己輸入 dic1 = {'name': ['小明', '小紅', '狗蛋', '鐵柱'], 'age': [17, 20, 5, 40], 'sex': ['男', '女', '女', '男']} # 使用字典進行輸入 test_3 = pd.DataFrame(dic1, index=list('ABCD')) print(test_1, '\n') print(test_2, '\n') print(test_3, '\n')
2.查看數據情況
print('查看數據類型:\n', test_3.dtypes, '\n') print('看前兩行:\n', test_3.head(2), '\n') print('看后兩行:\n', test_3.tail(2), '\n') print('index看行名:\n', test_3.index, '\n') print('columns看行名:\n', test_3.columns, '\n')
3.數據檢索
print('看所有數據值:\n', test_3.values, '\n') print('查看name列的數據:\n', test_3['name'].values, '\n') print('使用loc進行行檢索:\n', test_3.loc['A'], '\n') print('使用iloc進行行檢索:\n', test_3.iloc[0], '\n') print('直接使用名字進行列檢索,但不適合行檢索:\n', test_3['name'], '\n')
4.對表進行描述
print('對表進行描述:\n', test_3.describe(), '\n')
5.表的合並
print('進行轉置:\n', test_3.T, '\n') print('查看行數:', test_3.shape[0], '查看列數:', test_3.shape[1], '\n') # print('對表進行描述:\n', test_3.describe(), '\n') test_3.insert(3, 'skin', ['b', 'w', 'w', 'y']) print('對表用insert進行插入:\n', test_3, '\n') test_4 = pd.DataFrame(['T', 'E', 'W', 'A'], index=list('ABCD'), columns=list('N')) # print('新建的DataFrame:\n', test_4, '\n') print('合並DataFrame:\n', test_3.join(test_4), '\n')