最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python Pandas基礎(chǔ)操作詳解

 更新時(shí)間:2021年10月27日 11:22:51   作者:沖浪的長頸鹿V  
這篇文章主要介紹了Python使用Pandas庫常見操作,結(jié)合實(shí)例形式詳細(xì)分析了Python Pandas模塊的功能、原理、數(shù)據(jù)對(duì)象創(chuàng)建、查看、選擇等相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下

數(shù)據(jù)結(jié)構(gòu)&Series:

'''
series {索引 + 數(shù)據(jù)} 形式
索引是自動(dòng)生成的
'''
#通過 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'])
#單獨(dú)查看值或索引
print(s1.values)
print(s1.index)
#字典索引超出 會(huì)顯示nan 值 不會(huì)像數(shù)組創(chuàng)建series一樣報(bào)錯(cuò)
#通過字典來創(chuàng)建series  由于字典無序 所以每次打印順序可能不同, 所以可以添加索引 保證順序
dict1 = {'姓名': '李寧', '班級(jí)': '三班', '年齡': '22'}
print(dict1)
s3 = pd.Series(dict1, index=['姓名', '班級(jí)', '年齡', '性別'])
#判斷values是否為空nan
print(s3.isnull())
#判斷values是否不為空
print(s3.notnull())
#通過下標(biāo)取數(shù)據(jù)
print(s3[1])
#通過標(biāo)簽名取數(shù)字
print(s3['姓名'])
#選取多個(gè)
print(s2[[1, 5]])
#切片取值
print(s2[1:4])              #索引切邊 是 左閉右開
print(s2['b':'h'])          #標(biāo)簽切片可以包含末端數(shù)據(jù) 如h
#bool索引取值
print(s2[s2>5])
#索引與數(shù)據(jù)的對(duì)應(yīng)關(guān)系 不被 運(yùn)算所影響
#name 屬性
s2.name = '佳林'          #數(shù)組對(duì)象名---values標(biāo)題
s2.index.name = '字母表'   #索引名  ---- index標(biāo)題
#查看前三行
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----默認(rèn)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)建一個(gè)符合新索引的新對(duì)象
ps2 = ps.reindex(['a', 'b', 'c', 'd', 'e'])
print(ps2)           #因?yàn)樾滤饕c之前的索引沒有對(duì)應(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一樣 進(jìn)行轉(zhuǎn)至 切片提取
# print(pd1.T)
print(pd1[:'B']['e'])          #第一個(gè)或只有一個(gè)[]默認(rèn)是行索引index 第二個(gè)[]是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進(jìn)行廣播操作 如整體去掉某符號(hào)
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是按標(biāo)簽提取
df.loc[:, 'a']                    #提取a列
df.loc[:, ['a', 'c']]             #提取ac列
df.loc[1]                         #提取行標(biāo)簽為1的行
df.iloc[1]                        #提取行位置為1的行也就是第二行
df.loc[:2]                        #提取多行
#loc沒有左閉右開
df.loc[0:1, 'b']                  #提取行索引0-1包括1 的‘b'列
df1.loc['a':'B', 'c':'d']         #按標(biāo)簽提取某范圍的行列
#多條件
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)]
 

廣播運(yùn)算:

arr = np.arange(12).reshape(3, 4)
print(arr)
#廣播 每一行都減去第一行
print(arr-arr[0])
#默認(rèn)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)
#沿著列運(yùn)算
print(df1.sub(s4, axis= 0))          

索引增刪改查:

#增
##series
ps[4] = 9
print(ps)
ps1 = pd.Series({'v': 's', 'f': 's'})
pss = ps.append(ps1)                 #append拼接 這個(gè)方法不會(huì)影響原有數(shù)據(jù)
##dataframe
###增加列
df['d'] = [9, 8, 9]
###插入
df.insert(0, 'M', 1)            #在第0列插入M全為1
##高級(jí)標(biāo)簽索引--增加行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
#修改單個(gè)元素
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)容!

相關(guān)文章

  • 解決python訓(xùn)練模型報(bào)錯(cuò):BrokenPipeError:?[Errno?32]?Broken?pipe

    解決python訓(xùn)練模型報(bào)錯(cuò):BrokenPipeError:?[Errno?32]?Broken?pipe

    這篇文章主要介紹了解決python訓(xùn)練模型報(bào)錯(cuò):BrokenPipeError:?[Errno?32]?Broken?pipe問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • python實(shí)現(xiàn)的一個(gè)p2p文件傳輸實(shí)例

    python實(shí)現(xiàn)的一個(gè)p2p文件傳輸實(shí)例

    這篇文章主要介紹了python實(shí)現(xiàn)的一個(gè)p2p文件傳輸實(shí)例,文中用來解決多臺(tái)服務(wù)器維護(hù)文件同步問題,需要的朋友可以參考下
    2014-06-06
  • pandas.loc 選取指定列進(jìn)行操作的實(shí)例

    pandas.loc 選取指定列進(jìn)行操作的實(shí)例

    今天小編就為大家分享一篇pandas.loc 選取指定列進(jìn)行操作的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05
  • Python?Pandas如何獲取和修改任意位置的值(at,iat,loc,iloc)

    Python?Pandas如何獲取和修改任意位置的值(at,iat,loc,iloc)

    在我們對(duì)數(shù)據(jù)進(jìn)行選擇之后,需要對(duì)特定的數(shù)據(jù)進(jìn)行設(shè)置更改,設(shè)置,下面這篇文章主要給大家介紹了關(guān)于Python?Pandas如何獲取和修改任意位置的值(at,iat,loc,iloc)的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-01-01
  • 深入探討Python復(fù)合型數(shù)據(jù)的常見陷阱與避免方法

    深入探討Python復(fù)合型數(shù)據(jù)的常見陷阱與避免方法

    在Python中,復(fù)合型數(shù)據(jù)(例如列表、元組、集合和字典)是非常常用的數(shù)據(jù)類型,本文將深入探討Python復(fù)合型數(shù)據(jù)的常見陷阱,并提供一些避免這些問題的實(shí)用建議和技巧,希望對(duì)大家有所幫助
    2024-03-03
  • django主動(dòng)拋出403異常的方法詳解

    django主動(dòng)拋出403異常的方法詳解

    這篇文章主要給大家介紹了關(guān)于django主動(dòng)拋出403異常的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-01-01
  • Pycharm常用快捷鍵總結(jié)及配置方法

    Pycharm常用快捷鍵總結(jié)及配置方法

    這篇文章主要介紹了Pycharm常用快捷鍵總結(jié)及配置方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11
  • python使用in操作符時(shí)元組和數(shù)組的區(qū)別分析

    python使用in操作符時(shí)元組和數(shù)組的區(qū)別分析

    有時(shí)候要判斷一個(gè)數(shù)是否在一個(gè)序列里面,這時(shí)就會(huì)用到in運(yùn)算符來判斷成員資格,如果條件為真時(shí),就會(huì)返回true,條件為假時(shí),返回一個(gè)flase。這樣的運(yùn)算符叫做布爾運(yùn)算符,其真值叫做布爾值。
    2015-05-05
  • Python入門教程(十六)Python的if邏輯判斷分支

    Python入門教程(十六)Python的if邏輯判斷分支

    這篇文章主要介紹了Python入門教程(十六)Python的if邏輯判斷分支,Python是一門非常強(qiáng)大好用的語言,也有著易上手的特性,本文為入門教程,需要的朋友可以參考下
    2023-04-04
  • Python基礎(chǔ)語言學(xué)習(xí)筆記總結(jié)(精華)

    Python基礎(chǔ)語言學(xué)習(xí)筆記總結(jié)(精華)

    給大家分享一篇關(guān)于Python基礎(chǔ)學(xué)習(xí)內(nèi)容的學(xué)習(xí)筆記整理總結(jié)篇,里面匯集了學(xué)習(xí)Python基礎(chǔ)語言的難點(diǎn)和技巧,分享給大家。
    2017-11-11

最新評(píng)論

济宁市| 琼中| 安阳市| 宝鸡市| 调兵山市| 阳新县| 高唐县| 灌云县| 大港区| 托克逊县| 萨迦县| 武功县| 上饶县| 大理市| 北安市| 射阳县| 花垣县| 咸丰县| 东明县| 新建县| 萝北县| 武隆县| 西盟| 新乐市| 新干县| 拉萨市| 义乌市| 苗栗市| 五莲县| 克什克腾旗| 永川市| 万荣县| 治多县| 虞城县| 萍乡市| 丰台区| 竹山县| 崇州市| 博野县| 阿克陶县| 崇仁县|