Python資料分析學習筆記——DataFrame(還在更新中)
pandas的官方文件
1.DataFrame
DataFrame是一個表格型的資料結構,它含有一組有序的列,每列可以是不同的值型別(數值、字串、布林值等)。DataFrame既有行索引也有列索引,它可以被看做由Series組成的字典(共用同一個索引)。
DataFrame可以通過類似字典的方式或者.columnname的方式將列獲取為一個Series。行也可以通過位置或名稱的方式進行獲取。
為不存在的列賦值會建立新列。
1.1建立DataFrame
pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
data:numpy ndarray(結構化或同類),dict或DataFrame,Dict可以包含Series,陣列,常量或類似列表的物件
index:dataframe的索引,如果沒有自定義,則預設為RangeIndex(0,1,2,…,n)
columns:dataframe的列標籤,如果沒有自定義,則預設為RangeIndex(0,1,2,…,n)
dtype:預設None,要強制的資料型別。 只允許一個dtype
copy:boolean,預設為False
1.2讀取檔案
- 讀取csv檔案
dfcsv = pd.DataFrame(pd.read_csv("name"))
- 讀取excel檔案
dfexcel = pd.DataFrame(pd.read_excel("name"))
- 讀取mysql資料庫檔案:需要用到sqlalchemy 和pymysql包
import pandas as pd from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:[email protected]:3306/classicmodels") sql = "select * from customers" dfsql = pd.read_sql_query(sql,engine) dfsql
root >> 伺服器名稱
123456 >> 資料庫伺服器密碼
localhost:3306 >> 資料庫地址
classicmodels >> 資料庫名稱
1.3檢視資料的維度
df.shape #輸出行數、列數
dfexcel.shape
(326, 7)
1.4檢視資料表基本資訊
dfexcel.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 326 entries, 0 to 325
Data columns (total 7 columns):
訂單編碼 326 non-null int64
訂單日期 326 non-null datetime64[ns]
要求發貨日期 326 non-null datetime64[ns]
實際發貨日期 312 non-null datetime64[ns]
訂單狀態 326 non-null object
備註 80 non-null object
顧客編碼 326 non-null int64
dtypes: datetime64[ns](3), int64(2), object(2)
memory usage: 17.9+ KB
dfsql.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 20 entries, 0 to 19
Data columns (total 6 columns):
訂單編碼 20 non-null int64
產品編碼 20 non-null object
訂購數量 20 non-null int64
單價 20 non-null float64
訂單子編碼 20 non-null int64
訂單金額 20 non-null float64
dtypes: float64(2), int64(3), object(1)
memory usage: 1.0+ KB
1.5獲取表、列資料
frame
frame[‘col1’]
frame.col1
dfexcel
dfexcel.訂單日期
dfexcel["訂單日期"]
1.6檢視空值
dfexcel.isnull()
dfexcel["col1"].isnull()
dfexcel["訂單日期"].isnull()
1.7檢視唯一值
dfexcel["col1"].unique()
dfexcel["訂單日期"].unique()
1.8查看錶列名
dfexcel.columns
1.9檢視前N行、後N行資料
dfexcel.head(10)
dfexcel.tail(10)
1.10新增列
1.10.1用eval函式新增計算列
inplace引數為是否替代當前DataFrame,預設為false
dfsql.eval("訂單金額 = 訂購數量 * 單價 ",inplace = True)
dfsql.columns
Index(['訂單編碼', '產品編碼', '訂購數量', '單價', '訂單子編碼', '訂單金額'], dtype='object')
一次新增多個計算列時
dfsql.eval("""訂單金額 = 訂購數量 * 單價
訂購數量1 = 訂購數量
單價1 = 單價
""",inplace = True);
dfsql.columns
Index(['訂單編碼', '產品編碼', '訂購數量', '單價', '訂單子編碼', '訂單金額', '訂購數量1', '單價1'], dtype='object')
1.10.2 用insert函式插入列
DataFrame.insert("location", new_name_column, value_inserted_column)
location:插入的索引位置,從0開始
new_name_column:新列名稱
value_inserted_column:新列值
ins1 = dfsql.pop("訂單金額"); #刪除之前eval插入的計算列
print(dfsql.columns)
Index(['訂單編碼', '產品編碼', '訂購數量', '單價', '訂單子編碼', '訂單金額', '訂購數量1', '單價1'], dtype='object')
dfsql.insert(4,"訂單金額",ins1) #在第4索引列插入新列
print(dfsql.columns)
Index(['訂單編碼', '產品編碼', '訂購數量', '單價', '訂單金額', '訂單子編碼', '訂購數量1', '單價1'], dtype='object')
1.11刪除行列資料
1.11.1用pop函式
先看下官方文件介紹 >>>戳我看原連結
pandas的Github原始碼
DataFrame.pop(item)
從frame裡刪除專案並返回. 如果不存在則返回KeyError錯誤.
引數:item : str格式,要被刪除的列標籤(column label直譯的。應該是列名稱的意思)
返回值:已刪除的series
以上面的資料庫dfsql為例
print(dfsql.columns)
Index(['訂單編碼', '產品編碼', '訂購數量', '單價', '訂單金額', '訂單子編碼'], dtype='object')
dfsql.eval("訂單金額 = 訂購數量 * 單價",inplace = True) #先新增一列訂單金額.
print(dfsql)
訂單編碼 產品編碼 訂購數量 單價 訂單子編碼 訂單金額
0 10100 S18_1749 30 136.00 3 4080.00
1 10100 S18_2248 50 55.09 2 2754.50
2 10100 S18_4409 22 75.46 4 1660.12
3 10100 S24_3969 49 35.29 1 1729.21
4 10101 S18_2325 25 108.06 4 2701.50
5 10101 S18_2795 26 167.06 1 4343.56
6 10101 S24_1937 45 32.53 3 1463.85
7 10101 S24_2022 46 44.35 2 2040.10
8 10102 S18_1342 39 95.55 2 3726.45
9 10102 S18_1367 41 43.13 1 1768.33
10 10103 S10_1949 26 214.30 11 5571.80
11 10103 S10_4962 42 119.67 4 5026.14
12 10103 S12_1666 27 121.64 8 3284.28
13 10103 S18_1097 35 94.50 10 3307.50
14 10103 S18_2432 22 58.34 2 1283.48
15 10103 S18_2949 27 92.19 12 2489.13
16 10103 S18_2957 35 61.84 14 2164.40
17 10103 S18_3136 25 86.92 13 2173.00
print(dfsql.pop("訂單金額"))
0 4080.00
1 2754.50
2 1660.12
3 1729.21
4 2701.50
5 4343.56
6 1463.85
7 2040.10
8 3726.45
9 1768.33
10 5571.80
11 5026.14
12 3284.28
13 3307.50
14 1283.48
15 2489.13
16 2164.40
17 2173.00
Name: 訂單金額, dtype: float64
1.12.2 用del函式
del frame[‘col1’]
del frame.col1
del dfexcel.訂單日期
1.12.3用drop函式
pandas.DataFrame.drop官方文件 >>>戳我點連結
DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=‘raise’)
函式作用:從行或列刪除指定標籤。Drop specified labels from rows or columns.
通過指定的標籤名字和對應的軸,或者直接指定索引名稱或列名稱來刪除行或者列。
下面這句介紹每太搞清楚到底是何意思。
When using a multi-index, labels on different levels can be removed by
specifying the level.
引數介紹:
引數名稱 | 含義 | 介紹 |
---|---|---|
labels | 單獨的標籤或者類似的list | 要刪除的索引或者列標籤 |
axis | 0或者索引名稱,1或者列名稱 ,預設為0 | 確定從索引(或者axis = 0)還是列(或者axis = 1)刪除標籤 |
index / columns | 單個標籤或者類似list | 標籤值,axis = 1 等同於columns = 列名稱(也就是前兩個引數等同於第三個引數) |
level | int or level name optional(沒搞懂,反正可有可無。手動滑稽臉) | For MultiIndex, level from which the labels will be removed. |
inplace | 布林值,預設false | 如果為True,就在原資料上執行刪除操作,不返回任何值 |
errors | {‘ignore’, ‘raise’}, default ‘raise’ | If ‘ignore’, suppress error and only existing labels are dropped. |
返回值:
已刪除的pandas.DataFrame
Raises:
如果標籤不存在指定的軸上,返回KeyError
print(dfsql.columns)
Index(['訂單編碼', '產品編碼', '訂購數量', '單價', '訂單子編碼'], dtype='object')
dfsql.eval("訂單金額 = 訂購數量 * 單價",inplace = True)
print(dfsql.columns)
Index(['訂單編碼', '產品編碼', '訂購數量', '單價', '訂單子編碼', '訂單金額'], dtype='object')
dfsql.drop(["訂單金額"],axis = 1)
訂單編碼 產品編碼 訂購數量 單價 訂單子編碼
0 10100 S18_1749 30 136.00 3
1 10100 S18_2248 50 55.09 2
2 10100 S18_4409 22 75.46 4
3 10100 S24_3969 49 35.29 1
4 10101 S18_2325 25 108.06 4
5 10101 S18_2795 26 167.06 1
6 10101 S24_1937 45 32.53 3
7 10101 S24_2022 46 44.35 2
8 10102 S18_1342 39 95.55 2
9 10102 S18_1367 41 43.13 1
10 10103 S10_1949 26 214.30 11
11 10103 S10_4962 42 119.67 4
12 10103 S12_1666 27 121.64 8
13 10103 S18_1097 35 94.50 10
14 10103 S18_2432 22 58.34 2
15 10103 S18_2949 27 92.19 12
16 10103 S18_2957 35 61.84 14
17 10103 S18_3136 25 86.92 13
18 10103 S18_3320 46 86.31 16
19 10103 S18_4600 36 98.07 5
dfsql.drop(columns = ["訂單金額"])
# dfsql.drop(["訂單金額"],axis = 1)等同於dfsql.drop(columns = ["訂單金額"])
訂單編碼 產品編碼 訂購數量 單價 訂單子編碼
0 10100 S18_1749 30 136.00 3
1 10100 S18_2248 50 55.09 2
2 10100 S18_4409 22 75.46 4
3 10100 S24_3969 49 35.29 1
4 10101 S18_2325 25 108.06 4
5 10101 S18_2795 26 167.06 1
6 10101 S24_1937 45 32.53 3
7 10101 S24_2022 46 44.35 2
8 10102 S18_1342 39 95.55 2
9 10102 S18_1367 41 43.13 1
10 10103 S10_1949 26 214.30 11
11 10103 S10_4962 42 119.67 4
12 10103 S12_1666 27 121.64 8
13 10103 S18_1097 35 94.50 10
14 10103 S18_2432 22 58.34 2
15 10103 S18_2949 27 92.19 12
16 10103 S18_2957 35 61.84 14
17 10103 S18_3136 25 86.92 13
18 10103 S18_3320 46 86.31 16
19 10103 S18_4600 36 98.07 5
2.pandas.date_range()
2.1語法
pandas.date_range(start=None, end=None, periods=None, freq=‘D’,tz=None, normalize=False, name=None, closed=None)
該函式主要用於生成一個固定頻率的時間索引,在呼叫構造方法時,必須指定start、end、periods中的兩個引數值,否則報錯。
2.2主要引數說明
start:開始日期,例如:‘20180101’,‘01/01/2018’
end:結束日期
periods:固定時期,取值為整數或None;
freq:日期偏移量,取值為string或DateOffset,預設為’D’,還有’M’,‘Q’,‘Y’
normalize:若引數為True表示將start、end引數值規範化到午夜時間20180101 00:00:00
name:生成時間索引物件的名稱,取值為string或None
closed:可以理解成在closed=None情況下返回的結果中,若closed=‘left’表示在返回的結果基礎上,再取左開右閉的結果,若closed='right’表示在返回的結果基礎上,再取做閉右開的結果
示例:date_range = pd.date_range('20180101', periods=10, freq='D')
輸出:DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04', '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08','2018-01-09', '2018-01-10'],dtype='datetime64[ns]', freq='D')
引數 | 說明 |
---|---|
D | 天 |
B | 工作日 |
MS | 月第一天 |
BMS | 月第一個工作日 |
M | 月最後一天 |
BM | 月最後一個工作日 |
Q | 季度末 |
Y | 年末 |
H | 小時 |
min | 分鐘 |
S | 秒 |
W-MON、W-TUE | 每週,並指定每週從周幾開始 |