随笔 - 363, 文章 - 0, 评论 - 2, 阅读 - 23万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

04如何遍历pandas当中dataframe的元素

Posted on   心默默言  阅读(3283)  评论(0编辑  收藏  举报

04如何遍历pandas当中dataframe的元素

In [1]:
import pandas as pd
In [2]:
inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]
df = pd.DataFrame(inp)
df
Out[2]:
 
 c1c2
0 10 100
1 11 110
2 12 120
 

与此相关的有如下:

iterrows() : 将DataFrame迭代成(index ,series)

iteritems(): 将DataFrame迭代成(列名,series)

itertuples(): 将DataFrame迭代成元组

方法一:df.iterrows()

In [11]:
for index, row in df.iterrows():
    print(index, row["c1"], row["c2"])
 
0 10 100
1 11 110
2 12 120
In [14]:
for name, col in df.iteritems():
    print(name)
    print(col)
 
c1
0    10
1    11
2    12
Name: c1, dtype: int64
c2
0    100
1    110
2    120
Name: c2, dtype: int64
In [18]:
for i in df.itertuples():
    print(i)
    print(getattr(i, 'c1'), getattr(i, 'c2'))
 
Pandas(Index=0, c1=10, c2=100)
10 100
Pandas(Index=1, c1=11, c2=110)
11 110
Pandas(Index=2, c1=12, c2=120)
12 120
In [19]:
for i in df.itertuples(index=True, name='Pandas'):
    print(i)
    print(getattr(i, 'c1'), getattr(i, 'c2'))
 
Pandas(Index=0, c1=10, c2=100)
10 100
Pandas(Index=1, c1=11, c2=110)
11 110
Pandas(Index=2, c1=12, c2=120)
12 120
In [20]:
for i in df.itertuples(index=False, name='nihao'):
    print(i)
    print(getattr(i, 'c1'), getattr(i, 'c2'))
 
nihao(c1=10, c2=100)
10 100
nihao(c1=11, c2=110)
11 110
nihao(c1=12, c2=120)
12 120
 

第二种方案: applymap() 函数可以对DataFrame里的每个值进行处理,然后返回一个新的DataFrame

In [22]:
df = pd.DataFrame({
    'a': [1, 2, 3],
    'b': [10, 20, 30],
    'c': [5, 10, 15]
})
df
Out[22]:
 
 abc
0 1 10 5
1 2 20 10
2 3 30 15
In [23]:
def add_one(x):
    return x + 1
df.applymap(add_one)
Out[23]:
 
 abc
0 2 11 6
1 3 21 11
2 4 31 16
 

一个栗子:

这里有一组数据是10个学生的两次考试成绩,要求把成绩转换成ABCD等级:</br>

转换规则是:</br>

90-100 -> A</br> 80-89 -> B</br> 70-79 -> C</br> 60-69 -> D</br> 0-59 -> F</br>

In [24]:
grades_df = pd.DataFrame(
    data={'exam1': [43, 81, 78, 75, 89, 70, 91, 65, 98, 87],
          'exam2': [24, 63, 56, 56, 67, 51, 79, 46, 72, 60]},
    index=['Andre', 'Barry', 'Chris', 'Dan', 'Emilio',
           'Fred', 'Greta', 'Humbert', 'Ivan', 'James']
)
grades_df
Out[24]:
 
 exam1exam2
Andre 43 24
Barry 81 63
Chris 78 56
Dan 75 56
Emilio 89 67
Fred 70 51
Greta 91 79
Humbert 65 46
Ivan 98 72
James 87 60
In [25]:
def convert_to_letter(score):
    if (score >= 90):
        return 'A'
    elif (score >= 80):
        return 'B'
    elif (score >= 70):
        return 'C'
    elif (score >= 60):
        return 'D'
    else:
        return 'F'
grades_df.applymap(convert_to_letter)
Out[25]:
 
 exam1exam2
Andre F F
Barry B D
Chris C F
Dan C F
Emilio B D
Fred C F
Greta A C
Humbert D F
Ivan A C
James B D
 

第三种方案:iloc

In [26]:
df = pd.DataFrame({
    'a': [1, 2, 3],
    'b': [10, 20, 30],
    'c': [5, 10, 15]
})
df
Out[26]:
 
 abc
0 1 10 5
1 2 20 10
2 3 30 15
In [28]:
for i in range(0, len(df)):
    print(df.iloc[i]['a'], df.iloc[i]['b'],df.iloc[i]['c'])
 
1 10 5
2 20 10
3 30 15
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示