Python Pandas基礎(chǔ)操作詳解
更新時間:2021年10月27日 11:22:51 作者:沖浪的長頸鹿V
這篇文章主要介紹了Python使用Pandas庫常見操作,結(jié)合實例形式詳細分析了Python Pandas模塊的功能、原理、數(shù)據(jù)對象創(chuàng)建、查看、選擇等相關(guān)操作技巧與注意事項,需要的朋友可以參考下
數(shù)據(jù)結(jié)構(gòu)&Series:
'''
series {索引 + 數(shù)據(jù)} 形式
索引是自動生成的
'''
#通過 list 創(chuàng)建
s1 = pd.Series([1, 2, 3, 4, 5])
#通過np數(shù)組創(chuàng)建
arr1 = np.arange(10)
s2 = pd.Series(arr1)
#自定義索引
s2 = pd.Series(arr1, index=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])
#單獨查看值或索引
print(s1.values)
print(s1.index)
#字典索引超出 會顯示nan 值 不會像數(shù)組創(chuàng)建series一樣報錯
#通過字典來創(chuàng)建series 由于字典無序 所以每次打印順序可能不同, 所以可以添加索引 保證順序
dict1 = {'姓名': '李寧', '班級': '三班', '年齡': '22'}
print(dict1)
s3 = pd.Series(dict1, index=['姓名', '班級', '年齡', '性別'])
#判斷values是否為空nan
print(s3.isnull())
#判斷values是否不為空
print(s3.notnull())
#通過下標取數(shù)據(jù)
print(s3[1])
#通過標簽名取數(shù)字
print(s3['姓名'])
#選取多個
print(s2[[1, 5]])
#切片取值
print(s2[1:4]) #索引切邊 是 左閉右開
print(s2['b':'h']) #標簽切片可以包含末端數(shù)據(jù) 如h
#bool索引取值
print(s2[s2>5])
#索引與數(shù)據(jù)的對應(yīng)關(guān)系 不被 運算所影響
#name 屬性
s2.name = '佳林' #數(shù)組對象名---values標題
s2.index.name = '字母表' #索引名 ---- index標題
#查看前三行
print(s2.head(3))
#查看后兩行
print(s2.tail(2))
DataFrame的構(gòu)建:
#構(gòu)造多類型字典
data = {
'a': [1, 2, 3, 4],
'b': (5, 6, 7, 8),
'c': np.arange(9, 13)
}
frame = pd.DataFrame(data)
#查看行索引
print(frame.index)
#查看列索引
print(frame.columns)
#查看values
print(frame.values) #返回nparray類型的二維數(shù)組
#指定行索引
frame = pd.DataFrame(data, index=['A', 'B', 'C', 'D'])
#指定列行索引
frame = pd.DataFrame(data, index=['A', 'B', 'C', 'D'], columns=['a', 'b', 'c', 'd'])
#series構(gòu)成的字典構(gòu)造dataframe
pd1 = pd.DataFrame({'a': pd.Series(np.arange(5)),
'b': pd.Series(np.arange(3, 5))
})
#dataframe的每列元素類型必須統(tǒng)一
#通過字典構(gòu)造的字典來構(gòu)造dataframe(嵌套)
data1 = {
'a': {
'apple': '3.6',
'banan': '3.5'
},
'b': {
'apple': '3.6',
'banan': '3.5',
'red': '3.7',
'yellow': '3.8'
}
}
#最內(nèi)層字典的key是index
#外層字典的key是columns
#通過二位數(shù)組來構(gòu)造dataframe----默認columns和index都是0-n
arr1 = np.arange(12).reshape(3, 4)
print(arr1)
frame1 = pd.DataFrame(arr1)
#字典構(gòu)造的列表 構(gòu)造 dataframe
li = [{'apple': '3.6', 'orange': '2.5'}, {'apple': '4.8', 'orange': '2.8'}, {'apple': '2.4'}]
li_data = pd.DataFrame(li)
#Series構(gòu)成的列表 構(gòu)成dataframe
l2 = [pd.Series(np.random.rand(3)), pd.Series(np.random.rand(3))]
l2_data = pd.DataFrame(l2)
索引操作:
ps = pd.Series(range(5))
pd1 = pd.DataFrame(np.arange(9).reshape(3, 3),
index=['a', 'b', 'c'], columns=['A', 'B', 'C'])
#重新索引 reindex 創(chuàng)建一個符合新索引的新對象
ps2 = ps.reindex(['a', 'b', 'c', 'd', 'e'])
print(ps2) #因為新索引與之前的索引沒有對應(yīng)關(guān)系 所以values全為空!?。?!
#dataframe行索引重建順序調(diào)整
pd2 = pd1.reindex(['a', 'b', 'c', 'd'])
pd3 = pd1.reindex(columns= ['B', 'C', 'A', 'B'])
DataFrame基本操作:
np.random.seed(1)
pd1 = pd.DataFrame(np.random.randint(0, 10, size=(3, 5)), columns=['a', 'b', 'c', 'd', 'e'], index=['A', 'B', 'C'])
print(pd1)
#和numpy一樣 進行轉(zhuǎn)至 切片提取
# print(pd1.T)
print(pd1[:'B']['e']) #第一個或只有一個[]默認是行索引index 第二個[]是columns
#增加列
pd1['f'] = [5, 5, 5]
print(pd1)
#刪除列
del(pd1['d'])
print(pd1)
#修改行索引名----只能賦值
1\直接賦值法
pd1.index = ['a', 'b'........]
2\自定義函數(shù)法
def test_map(x):
return x+'_ABC'
pd1.rename(index=test_map,inplace=True)
#修改列索引名
1\直接賦值
pd1.columns = []
2\用str進行廣播操作 如整體去掉某符號
pd1.columns = pd1.columns.str.strip('$')
3\函數(shù)法
pd1.columns = pd1.columns.map(lambda x:x[1:])
4\rename屬性
# 直接法(好處:也可只修改特定的列)----字典values替代key
df.rename(columns=('$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}, inplace=True)
# 函數(shù)法
df.rename(columns=lambda x:x.replace('$',''), inplace=True)
#提取行、列的loc和iloc
#iloc是按索引位置提取
#loc是按標簽提取
df.loc[:, 'a'] #提取a列
df.loc[:, ['a', 'c']] #提取ac列
df.loc[1] #提取行標簽為1的行
df.iloc[1] #提取行位置為1的行也就是第二行
df.loc[:2] #提取多行
#loc沒有左閉右開
df.loc[0:1, 'b'] #提取行索引0-1包括1 的‘b'列
df1.loc['a':'B', 'c':'d'] #按標簽提取某范圍的行列
#多條件
df[(df['a']<=2) & (df['b']>=5)]
df.loc[(df['a']<=2) & (df['b']>=5)]
# 或 條件 不能使用 or
df[(df['a']<=2) | (df['b']>=5)]
df.loc[(df['a']<=2) | (df['b']>=5)]
廣播運算:
arr = np.arange(12).reshape(3, 4)
print(arr)
#廣播 每一行都減去第一行
print(arr-arr[0])
#默認series的行索引 匹配的是dataframe的列索引
df1 = pd.DataFrame(np.arange(12).reshape(4, 3), index=['a', 'b', 'c', 'd'], columns=list('ABC'))
s3 = df1.iloc[0] #取第一行
print(s3)
print(df1 - s3)
#沿著列運算
print(df1.sub(s4, axis= 0))
索引增刪改查:
#增
##series
ps[4] = 9
print(ps)
ps1 = pd.Series({'v': 's', 'f': 's'})
pss = ps.append(ps1) #append拼接 這個方法不會影響原有數(shù)據(jù)
##dataframe
###增加列
df['d'] = [9, 8, 9]
###插入
df.insert(0, 'M', 1) #在第0列插入M全為1
##高級標簽索引--增加行l(wèi)oc
df.loc['q'] = 1
row = {'M': 's', 'a': 'b', 'b': 'w', 'c': 'w', 'd': 8}
dfnew = df.append(row, ignore_index=True) #ignore_index:如果設(shè)置為true,則無視表的index,直接合并,合并后生成新的index。
#刪
del ps[0]
#del只能刪除dataframe的列
del df['M']
#*******drop******刪除軸上的數(shù)據(jù)
#dataframe刪除行
print(df.drop(['S', 'W']))
#指定軸刪除列
print(df.drop(['a', 'c'], axis=1))
ps = pd.Series(range(1, 5))
#改
ps[0] = 888
print(ps)
df.a = 6
#修改行數(shù)據(jù)
df.loc['S'] = 888
#修改單個元素
df.loc['D', 'b'] = 8848
字符串元素處理:
in:
data = {'a': 'aeac@qq.com', 'b': 'stevan@famil.com', 'c': 'asda@asd.com', 'd': np.nan}
data = pd.Series(data)
print(data)
print(data.isnull())
#字符串查找
print(data.str.contains('qq'))
#分割
print(data.str.split(r'@'))
print(data.str.findall(r'@'))
#切片
print(data.str[:5])
out:
a aeac@qq.com b stevan@famil.com c asda@asd.com d NaN dtype: object a False b False c False d True dtype: bool a True b False c False d NaN dtype: object a [aeac, qq.com] b [stevan, famil.com] c [asda, asd.com] d NaN dtype: object a [@] b [@] c [@] d NaN dtype: object a aeac@ b steva c asda@ d NaN dtype: object
數(shù)據(jù)規(guī)整:
pd.merge(data1, data2, on= '按照哪一行合并', how = 'left或right或outer或inner')
pd.merge(df_obj5, df_obj6, how='outer', left_index=True, right_index=True)
pd.merge(df_obj3, df_obj4, left_on='key', right_index=True)
pd.concat([df1, df2], join='inner\outer', axis=1
stack 列索引在最外層 columns在內(nèi)層 變成series
外層索引為index內(nèi)層索引變成columns--unstack()
g = df1.groupby(by='fruit')
for name,group in g:
print(name)
print('-'*30)
print(group)
apple
------------------------------
fruit color price
0 apple red 8.5
3 apple cyan 7.8
banana
------------------------------
fruit color price
1 banana yellow 6.8
4 banana cyan 6.4
orange
------------------------------
fruit color price
2 orange yellow 5.6
#利用字典來獲取具體分組名的dataframe
s = dict(list(df1.groupby(by='fruit')))
s['apple']
def diff(arr):
return arr.max() - arr.min()
df1.groupby(by='fruit')['price'].agg(diff)
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
您可能感興趣的文章:
- Python基礎(chǔ)之pandas數(shù)據(jù)合并
- 一文搞懂Python中pandas透視表pivot_table功能
- python優(yōu)化數(shù)據(jù)預(yù)處理方法Pandas pipe詳解
- Python Pandas兩個表格內(nèi)容模糊匹配的實現(xiàn)
- Python Pandas數(shù)據(jù)分析之iloc和loc的用法詳解
- python中pandas輸出完整、對齊的表格的方法
- Python Pandas高級教程之時間處理
- Python教程pandas數(shù)據(jù)分析去重復(fù)值
- 一文搞懂Python中Pandas數(shù)據(jù)合并
相關(guān)文章
解決python訓(xùn)練模型報錯:BrokenPipeError:?[Errno?32]?Broken?pipe
這篇文章主要介紹了解決python訓(xùn)練模型報錯:BrokenPipeError:?[Errno?32]?Broken?pipe問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07
Python?Pandas如何獲取和修改任意位置的值(at,iat,loc,iloc)
在我們對數(shù)據(jù)進行選擇之后,需要對特定的數(shù)據(jù)進行設(shè)置更改,設(shè)置,下面這篇文章主要給大家介紹了關(guān)于Python?Pandas如何獲取和修改任意位置的值(at,iat,loc,iloc)的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-01-01
深入探討Python復(fù)合型數(shù)據(jù)的常見陷阱與避免方法
在Python中,復(fù)合型數(shù)據(jù)(例如列表、元組、集合和字典)是非常常用的數(shù)據(jù)類型,本文將深入探討Python復(fù)合型數(shù)據(jù)的常見陷阱,并提供一些避免這些問題的實用建議和技巧,希望對大家有所幫助2024-03-03
python使用in操作符時元組和數(shù)組的區(qū)別分析
有時候要判斷一個數(shù)是否在一個序列里面,這時就會用到in運算符來判斷成員資格,如果條件為真時,就會返回true,條件為假時,返回一個flase。這樣的運算符叫做布爾運算符,其真值叫做布爾值。2015-05-05
Python基礎(chǔ)語言學(xué)習(xí)筆記總結(jié)(精華)
給大家分享一篇關(guān)于Python基礎(chǔ)學(xué)習(xí)內(nèi)容的學(xué)習(xí)筆記整理總結(jié)篇,里面匯集了學(xué)習(xí)Python基礎(chǔ)語言的難點和技巧,分享給大家。2017-11-11

