python?dataframe獲得指定行列簡(jiǎn)單例子
使用pandas庫(kù)中的DataFrame對(duì)象,可以通過(guò)行標(biāo)簽和列標(biāo)簽來(lái)獲取某個(gè)或某些行列的數(shù)據(jù)。
獲取行:
- 通過(guò)行標(biāo)簽(索引)獲取一行數(shù)據(jù):
df.loc[row_label]
- 通過(guò)行號(hào)(位置)獲取一行數(shù)據(jù):
df.iloc[row_index]
- 通過(guò)條件篩選獲取多行數(shù)據(jù):
df[df['column_name'] == 'value']
獲取列:
- 通過(guò)列標(biāo)簽獲取一列數(shù)據(jù):
df[column_label]
- 通過(guò)列標(biāo)簽獲取多列數(shù)據(jù):
df[[column_label1, column_label2]]
同時(shí)獲取指定的行和列:
- 通過(guò)行標(biāo)簽和列標(biāo)簽獲取指定的行和列數(shù)據(jù):
df.loc[row_label, column_label]
- 通過(guò)行號(hào)和列號(hào)獲取指定的行和列數(shù)據(jù):
df.iloc[row_index, column_index]
舉個(gè)例子:
import pandas as pd # 創(chuàng)建一個(gè)DataFrame data = {'name': ['Alice', 'Bob', 'Cathy', 'David'], 'age': [25, 30, 35, 40], 'gender': ['female', 'male', 'female', 'male'], 'score': [90, 85, 80, 75]} df = pd.DataFrame(data, columns=['name', 'age', 'gender', 'score']) # 獲取第2行數(shù)據(jù) print(df.iloc[1]) # 獲取gender列的數(shù)據(jù) print(df['gender']) # 獲取第3行的score列數(shù)據(jù) print(df.loc[2, 'score'])
附:pandas取dataframe特定行列實(shí)例
將男性(m)替換為1,女性(f)替換為0
方法1:
代碼如下:
df.ix[df['sex']=='f','sex']=0 df.ix[df['sex']=='m','sex']=1
注:在上面的代碼中,逗號(hào)后面的‘sex'起到固定列名的作用
方法2:
代碼如下:
df.sex[df['sex']=='m']=1 df.sex[df['sex']=='f']=0
總結(jié)
到此這篇關(guān)于python dataframe獲得指定行列的文章就介紹到這了,更多相關(guān)python dataframe獲得指定行列內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python統(tǒng)計(jì)RGB圖片某像素的個(gè)數(shù)案例
這篇文章主要介紹了python統(tǒng)計(jì)RGB圖片某像素的個(gè)數(shù)案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03利用python3隨機(jī)生成中文字符的實(shí)現(xiàn)方法
最近在學(xué)習(xí)python3,發(fā)現(xiàn)網(wǎng)上關(guān)于ptyhon3隨機(jī)生成中文的資料非常少,所以決定將自己實(shí)現(xiàn)的方法分享下,下面這篇文章主要給大家介紹了關(guān)于利用python3隨機(jī)生成中文字符的實(shí)現(xiàn)方法,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-11-11

Python使用wxPython實(shí)現(xiàn)計(jì)算器

Python使用MapReduce編程模型統(tǒng)計(jì)銷量

Python使用zip合并相鄰列表項(xiàng)的方法示例

python沒(méi)有g(shù)pu,如何改用cpu跑代碼