欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python pandas遍歷行數(shù)據(jù)的2種方法小結(jié)

 更新時間:2024年03月31日 16:29:14   作者:數(shù)據(jù)人阿多  
pandas在數(shù)據(jù)處理過程中,除了對整列字段進行處理之外,有時還需求對每一行進行遍歷,本文就來介紹Python pandas遍歷行數(shù)據(jù)的2種方法小結(jié),感興趣的可以了解一下

背景

pandas在數(shù)據(jù)處理過程中,除了對整列字段進行處理之外,有時還需求對每一行進行遍歷,來處理每行的數(shù)據(jù)。本篇文章介紹 2 種方法,來遍歷pandas 的行數(shù)據(jù)

小編環(huán)境

import sys
print('python 版本:',sys.version.split('|')[0])   
#python 版本: 3.11.5
import pandas as pd
print(pd.__version__)
#2.1.0

演示數(shù)據(jù)

演示數(shù)據(jù)

方法1

pandas.DataFrame.itertuples:返回的是一個命名元組
官方文檔:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.itertuples.html

1. 無任何參數(shù)

import pandas as pd
data=pd.read_excel("data.xlsx")

for row in data.itertuples():
    print("row:",row,"\n")
    #row: Pandas(Index=0, 序號=1, 分割字符='1&1&1', 固定寬度='111') 
    
    print("type(row):",type(row),"\n")
    #type(row): <class 'pandas.core.frame.Pandas'> 
    
    print("row.序號:",row.序號)
    #row.序號: 1
    
    print("row.分割字符:",row.分割字符)
    #row.分割字符: 1&1&1
    
    print("row.固定寬度:",row.固定寬度)
    #row.固定寬度: 111
    
    break

2. 忽略掉索引

import pandas as pd
data=pd.read_excel("data.xlsx")

for row in data.itertuples(index=False):  #忽律索引
    print("row:",row,"\n")
    #row: Pandas(序號=1, 分割字符='1&1&1', 固定寬度='111') 
    
    print("type(row):",type(row),"\n")
    #type(row): <class 'pandas.core.frame.Pandas'> 
    
    print("row.序號:",row.序號)
    #row.序號: 1
    
    print("row.分割字符:",row.分割字符)
    #row.分割字符: 1&1&1
    
    print("row.固定寬度:",row.固定寬度)
    #row.固定寬度: 111
    
    break

3. 對命名元組起別名

import pandas as pd
data=pd.read_excel("data.xlsx")

for row in data.itertuples(index=False,name="data"):
    print("row:",row,"\n")
    #row: data(序號=1, 分割字符='1&1&1', 固定寬度='111')  
    
    print("type(row):",type(row),"\n")
    #type(row): <class 'pandas.core.frame.data'> 
    
    print("row.序號:",row.序號)
    #row.序號: 1
    
    print("row.分割字符:",row.分割字符)
    #row.分割字符: 1&1&1
    
    print("row.固定寬度:",row.固定寬度)
    #row.固定寬度: 111
    
    break

方法2

pandas.DataFrame.iterrows:返回 (index, Series) 元組
官方文檔:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html

import pandas as pd
data=pd.read_excel("data.xlsx")

for index,row in data.iterrows():
    print("index:",index,"\n")
    #index: 0
    
    print("row:",row,"\n")
    #row: 序號          1
    #分割字符    1&1&1
    #固定寬度      111
    #Name: 0, dtype: object
    
    print("type(row):",type(row),"\n")
    #type(row): <class 'pandas.core.series.Series'> 
    
    print("row['序號']:",row['序號'])
    #row['序號']: 1
    
    print("row['分割字符']:",row['分割字符'])
    #row['分割字符']: 1&1&1
    
    print("row['固定寬度']:",row['固定寬度'])
    #row['固定寬度']: 111
    
    break

到此這篇關(guān)于Python pandas遍歷行數(shù)據(jù)的2種方法小姐的文章就介紹到這了,更多相關(guān)pandas遍歷行內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

最新評論