Python Pandas
1.官網(wǎng)
https://pandas.pydata.org/docs/user_guide/10min.html
01.讀寫Excel:
import pandas as pd
# 讀取Excel幫助Link :https://pandas.pydata.org/docs/user_guide/io.html#excel-files
file = 'student_excel.xlsx'
# 1. 讀取Excel單個Sheet
df = pd.read_excel(file)
# 2. 查看數(shù)據(jù)頭,數(shù)據(jù)尾,數(shù)據(jù)形狀,數(shù)據(jù)類型
# df.head() / df.tail() / df.shape / df.dtypes
# 2. 讀取同一個Excel多個Sheet
with pd.ExcelFile(file) as excel:
df1 = pd.read_excel(excel, "Sheet1")
df2 = pd.read_excel(excel, "Sheet2")
print(df1)
# 3. 讀取Excel的所有Sheet :sheet_name= None, sheet_name 默認(rèn)為0讀取第一個Sheet
dfs = pd.read_excel(file, sheet_name=None)
for tdf in dfs.items():
print(tdf)
# 4.讀取指定的多個Sheet。Returns the 1st and 4th sheet, as a dictionary of DataFrames.
pd.read_excel(file, sheet_name=["Sheet1", 3])
output_file_path = 'Processed_Excel.xlsx'
# 5.輸出單個df到Excel文件
df.to_excel(output_file_path, sheet_name="Sheet1")
# 6.輸出多個DF到Excel文件,mode='a'為追加
with pd.ExcelWriter(output_file_path, mode='w') as writer:
df1.to_excel(writer, sheet_name='Sheet1', index=False)
df2.to_excel(writer, sheet_name='Sheet2', index=False)
02.讀寫數(shù)據(jù)庫:
import pandas as pd
import sqlalchemy
# 創(chuàng)建數(shù)據(jù)庫連接引擎
engine = sqlalchemy.create_engine(f'mysql+pymysql://{username}:{password}@{host}:{port}/{database}', echo=True)
# 使用 pandas 讀取數(shù)據(jù)
user_df = pd.read_sql("SELECT * FROM user", engine)
print(user_df)
# 移除自增字段列ID
df_filtered = user_df.drop(columns=['id'])
# 將 DataFrame 寫入 MySQL user_copy數(shù)據(jù)表中 (因為有自增字段id)
df_filtered.to_sql("user_copy", con=engine, if_exists='append', index=False)
03.數(shù)據(jù)結(jié)構(gòu)Series:
import numpy as np
import pandas as pd
# 方式1 :直接創(chuàng)建Series,不指定索引
s1 = pd.Series([1, 2, 3, 'xyz', 5])
print(s1.index) # Series索引
print(s1.values) # Series 值
# 方式2 :指定Series的索引名稱
s2 = pd.Series(np.random.randn(5), index=["a", "b", "c", "d", "e"])
print(s2)
# 方式3 :使用字典創(chuàng)建Series
s3 = pd.Series({"a": 1, "b": 2, "c": 3, "d": 4, "e": 5})
# 查詢Series數(shù)據(jù)
print(s3["a"])
# 查詢Series多個數(shù)據(jù)
print(s3[["a", "b", "c"]])
# 使用索引查詢Series數(shù)據(jù)
print(s3[s3 > 2])
# Series 切片1
print(s3[1:3])
# Series 切片2 eg:s.iloc[:3]
print(s3.iloc[[4, 3, 1]])
# 查詢Series的類型 or Series.dtype
print(type(s3["a"]))
# 創(chuàng)建Series, 整個列表值相同
s4 = pd.Series(5.0, index=["a", "b", "c", "d", "e"])
print(s4)
# 使用Series.get()方法時,缺少的標(biāo)簽將返回None或指定的默認(rèn)值
data = s4.get("f", np.nan)
print(data)
# Series 可以直接計算
print(s3+s4)
04.數(shù)據(jù)結(jié)構(gòu)DataFrame:
import numpy as np import pandas as pd dic_data = { "one": pd.Series([2, 2.0, 3.0], index=["a", "b", "c"]), "two": pd.Series([5, 6, 7, 8], index=["a", "b", "c", "d"]), } df = pd.DataFrame(dic_data) # 從字典中取部分值形成一個DataFrame df2 = pd.DataFrame(dic_data, index=["c", "b", "a"], columns=["one", "two", "new null column"]) print(df2) # 查詢DataFrame的行索引和列索引,查看每列的類型 print(df2.index) / print(df2.columns) / print(df2.dtypes) # 使用DataFrame.from_dict構(gòu)造一個按列索引的DataFrame,默認(rèn)orient參數(shù)是'columns' df3 = pd.DataFrame.from_dict(dict([("column A", [1, 2, 3]), ("column B", [4, 5, 6])])) # 使用DataFrame.from_dict構(gòu)造一個按行索引的DataFrame,orient="index"指定為行索引 df4 = pd.DataFrame.from_dict( dict([("row A", [1, 2, 3]), ("row B", [4, 5, 6])]), orient="index", columns=["column1", "column2", "column3"], ) # DataFrame的列選擇 print(df2["one"]) # 01. DataFrame的列新增 ,df2 已改變 df2["three"] = df2["one"] * df2["two"] # 01.2. DataFrame的列新增 assign函數(shù) ,df2為改變,結(jié)果在df5中 df5 = df2.assign(five=df2['one'] * df2['two']) print(df2["three"]) # 列刪除 del df2["two"] 或者 three = df.2pop("three") three = df2.pop("three") # 刪除列并返回被刪除的列 df2["four"] = '整列常量' # 插入列 df2.insert(1, 'column3 name', three) # 選擇行 df.loc[label] or df.iloc[loc] row3 = df2.iloc[2] row2 = df2.loc['b'] # 切片選 第二行和第三行 df_part_row = df2[1:3] # bool 選擇滿足條件的行 df_part_row2 = df2[df2['one'] < 3] # 隨機數(shù) 生成大于uniform大于20.0,小于30.0 的10行4列的隨機數(shù) # (或np.random.randn函數(shù)生成隨機符合正態(tài)分布的單個數(shù),列表,多維數(shù)等) random_numbers = np.random.uniform(20.0, 30.0, (10, 4)) # DataFrame 行列轉(zhuǎn)換 請訪問T屬性或DataFrame.transpose() print(df2.T)

04.Pandas查詢數(shù)據(jù)的5種方法:
import pandas as pd from numpy import int32 df = pd.read_csv(r'tianqi.csv') # 可選:將某列設(shè)置為索引列 df.set_index('ymd', inplace=True) # 將表格所有行,bWendu移除℃字符,為int類型 df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('℃', '', ).astype(int32) print(df) # 01.查詢單個值 loc[行索引,列索引] 得到一個值 df.loc['2018-07-01', 'bWendu'] # 02.查詢多個值,得到一個Series df.loc['2018-07-01', ['bWendu', 'yWendu']] # 02.查詢多行多列,得到一個DataFrame df.loc[['2018-07-01', '2018-07-02'], ['bWendu', 'yWendu']] # 03.查詢區(qū)間的值 loc[起始行索引:結(jié)束行索引,列索引] df.loc['2018-07-01':'2018-07-10', ['bWendu', 'yWendu']] # 03.查詢區(qū)間的值 loc[起始行索引:結(jié)束行索引,起始列索引:結(jié)束列索] df.loc['2018-07-01', 'bWendu':'fengxiang'] # 04.使用條件表達(dá)式進(jìn)行查詢 查詢bWendu > 10的行 (列索引:表明設(shè)置為所有列) df.loc[df['bWendu'] > 10, :] # 04.使用條件表達(dá)式進(jìn)行查詢 進(jìn)行多條件查詢 df.loc[(df['bWendu'] > 10) & (df['tianqi'] == '晴'), :] # 05. 使用函數(shù)進(jìn)行查詢 df.loc[lambda tdf: (tdf['bWendu'] > 10) & (tdf['tianqi'] == '晴'), :] # 05. 使用自定義函數(shù)QueryData進(jìn)行查詢 def QueryData(df): return (df['bWendu'] > 10) & (df['tianqi'] == '晴') df.loc[QueryData, :]
import numpy as np import pandas as pd data = { 'A': [1, 2, 3, 4], 'B': [10, 20, -30, 40], 'C': [100, 200, 300, 400] } df = pd.DataFrame(data) # 使用 where 方法篩選列 A 中值大于 2 的行,不滿足添加則將該位置的值置為0, 保留了一個和原DataFrame一樣格式和數(shù)量的數(shù)據(jù) filtered_df = df.where(df['A'] > 2, 0) # 使用 where 方法篩選單元格中值大于 1 的單元格,,不滿足添加則將該位置的值置為單元格的相反數(shù) filtered_df = df.where(df > 1, -df) # 對于不滿足單元格大于0的值,將該單元格填充為該行A列的值 filtered_df = df.where(df > 0, df['A'], axis='index') # mask 函數(shù)和Where函數(shù)相反,對于滿足條件的進(jìn)行填充處理,不滿足的不處理 masked_df = df.mask(df >= 0) # query 使用列名表達(dá)式進(jìn)行查詢,返回滿足條件的數(shù)據(jù) filtered_df = df.query('A < B and B < C') # query 索引列直接使用index關(guān)鍵字表示即可 filtered_df = df.query('index >= 1 and A < B ') df2 = pd.DataFrame({'a': ['one', 'one', 'two', 'two', 'two', 'three', 'four'], 'b': ['x', 'y', 'x', 'y', 'x', 'x', 'x'], 'c': np.random.randn(7)}) # 刪除a列重復(fù)的行,重復(fù)行,只保留第一次出現(xiàn)的行 keep in [ first,last,F(xiàn)alse],keep=False表示只要重復(fù)則全部刪除 df3 = df2.drop_duplicates(subset=['a'], keep='first') # 刪除索引重復(fù)的行,只保留最后一個索引行 df2[~df2.index.duplicated(keep='last')] # 新增一個new_index,并重新設(shè)置索引 reset_df_names = df.reset_index(names='new_index')
05.Pandas新增數(shù)據(jù)列:
import pandas as pd from numpy import int32 df = pd.read_csv(r'tianqi.csv') # 01.直接賦值 修改列 df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('℃', '', ) df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('℃', '', ) df['bWendu'] = df['bWendu'].astype(int32) df['yWendu'] = df['yWendu'].astype(int32) # 01.直接賦值 新增列WenCha df.loc[:, 'WenCha'] = df['bWendu'] - df['yWendu'] # 02. DadaFrame.Apply() 方法 colume: axis=1 ,row: axis=0 df['WenCha'] = df.apply(lambda x: x['bWendu'] - x['yWendu'], axis=1) def GetTemperatureType(t) -> str: if t['bWendu'] > 33: return '高溫' if t['yWendu'] < -10: return '低溫' return '常溫' df.loc[:, 'TemperatureType'] = df.apply(GetTemperatureType, axis=1) # 統(tǒng)計列中數(shù)值分別有多少個value_counts df.loc[:, 'TemperatureType'].value_counts() # 03.DadaFrame.assgin() 方法 ,同時賦值多個列,同時返回一個新的DadaFrame df2 df2 = df.assign( bWendu_huashi=lambda x: x['bWendu'] * 9 / 5 + 32, yWendu_huashi=lambda x: x['yWendu'] * 9 / 5 + 32 )
06.Pandas數(shù)據(jù)統(tǒng)計:
import pandas as pd from numpy import int32 df = pd.read_csv(r'tianqi.csv') df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('℃', '', ) df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('℃', '', ) df['bWendu'] = df['bWendu'].astype(int32) df['yWendu'] = df['yWendu'].astype(int32) print(df) # 匯總類統(tǒng)計 01.統(tǒng)計所有數(shù)字列的 數(shù)量 最大最小值 中位數(shù) 25% 75%分位數(shù)等 df.describe() # 匯總類統(tǒng)計 01.查看單個列的平均值 df['bWendu'].mean() #唯一去重 df['tianqi'].unique() #按值計數(shù) df['fengli'].value_counts() #協(xié)方差 :衡量同向反向程度 df.cov() #相關(guān)系數(shù):衡量相似度系數(shù) df.corr()

浙公網(wǎng)安備 33010602011771號