脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - pandas.DataFrame的for循环迭代的实现

pandas.DataFrame的for循环迭代的实现

2023-02-28 11:01饺子大人 Python

本文主要介绍了pandas.DataFrame的for循环迭代的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

当使用for语句循环(迭代)pandas.DataFrame时,简单的使用for语句便可以取得返回列名,因此使用重复使用for方法,便可以获取每行的值。

以下面的pandas.DataFrame为例。

?
1
2
3
4
5
6
7
8
9
import pandas as pd
 
df = pd.DataFrame({'age': [24, 42], 'state': ['NY', 'CA'], 'point': [64, 92]},
                  index=['Alice', 'Bob'])
 
print(df)
#        age state  point
# Alice   24    NY     64
# Bob     42    CA     92

在此对以下内容进行说明:

  • pandas.DataFrame for循环的应用
  • 逐列检索
    • DataFrame.iteritems()
  • 逐行检索
    • DataFrame.iterrows()
    • DataFrame.itertuples()
  • 检索特定列的值
  • 循环更新值

pandas.DataFrame for循环的应用

当pandas.DataFrame直接使用for循环时,按以下顺序获取列名(列名)。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for column_name in df:
    print(type(column_name))
    print(column_name)
    print('======\n')
# <class 'str'>
# age
# ======
#
# <class 'str'>
# state
# ======
#
# <class 'str'>
# point
# ======
#

调用方法__iter __()。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for column_name in df.__iter__():
    print(type(column_name))
    print(column_name)
    print('======\n')
# <class 'str'>
# age
# ======
#
# <class 'str'>
# state
# ======
#
# <class 'str'>
# point
# ======
#

逐列检索

DataFrame.iteritems()

使用iteritems()方法,您可以一一获取列名称(列名称)和元组(列名称,系列)的每个列的数据(pandas.Series类型)。

pandas.Series可以通过指定索引名称等来检索行的值。

?
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
for column_name, item in df.iteritems():
    print(type(column_name))
    print(column_name)
    print('~~~~~~')
 
    print(type(item))
    print(item)
    print('------')
 
    print(item['Alice'])
    print(item[0])
    print(item.Alice)
    print('======\n')
# <class 'str'>
# age
# ~~~~~~
# <class 'pandas.core.series.Series'>
# Alice    24
# Bob      42
# Name: age, dtype: int64
# ------
# 24
# 24
# 24
# ======
# <class 'str'>
# state
# ~~~~~~
# <class 'pandas.core.series.Series'>
# Alice    NY
# Bob      CA
# Name: state, dtype: object
# ------
# NY
# NY
# NY
# ======
# <class 'str'>
# point
# ~~~~~~
# <class 'pandas.core.series.Series'>
# Alice    64
# Bob      92
# Name: point, dtype: int64
# ------
# 64
# 64
# 64
# ======

逐行检索

一次检索一行的方法包括iterrows()和itertuples()。 itertuples()更快。

如果只需要特定列的值,则如下所述,指定列并将它们分别在for循环中进行迭代会更快。

DataFrame.iterrows()

通过使用iterrows()方法,可以获得每一行的数据(pandas.Series类型)和行名和元组(索引,系列)。

pandas.Series可以通过指定列名等来检索列的值。

?
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
32
33
34
35
36
37
38
39
40
for index, row in df.iterrows():
    print(type(index))
    print(index)
    print('~~~~~~')
 
    print(type(row))
    print(row)
    print('------')
 
    print(row['point'])
    print(row[2])
    print(row.point)
    print('======\n')
# <class 'str'>
# Alice
# ~~~~~~
# <class 'pandas.core.series.Series'>
# age      24
# state    NY
# point    64
# Name: Alice, dtype: object
# ------
# 64
# 64
# 64
# ======
# <class 'str'>
# Bob
# ~~~~~~
# <class 'pandas.core.series.Series'>
# age      42
# state    CA
# point    92
# Name: Bob, dtype: object
# ------
# 92
# 92
# 92
# ======

DataFrame.itertuples()

使用itertuples()方法,可以一一获取索引名(行名)和该行数据的元组。元组的第一个元素是索引名称。

默认情况下,返回一个名为Pandas的namedtuple。由于它是namedtuple,因此可以访问每个元素的值。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for row in df.itertuples():
    print(type(row))
    print(row)
    print('------')
 
    print(row[3])
    print(row.point)
    print('======\n')
# <class 'pandas.core.frame.Pandas'>
# Pandas(Index='Alice', age=24, state='NY', point=64)
# ------
# 64
# 64
# ======
# <class 'pandas.core.frame.Pandas'>
# Pandas(Index='Bob', age=42, state='CA', point=92)
# ------
# 92
# 92
# ======

如果参数name为None,则返回一个普通的元组。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
for row in df.itertuples(name=None):
    print(type(row))
    print(row)
    print('------')
 
    print(row[3])
    print('======\n')
# <class 'tuple'>
# ('Alice', 24, 'NY', 64)
# ------
# 64
# ======
# <class 'tuple'>
# ('Bob', 42, 'CA', 92)
# ------
# 92
# ======

检索特定列的值

上述的iterrows()和itertuples()方法可以检索每一行中的所有列元素,但是如果仅需要特定的列元素,可以使用以下方法。

pandas.DataFrame的列是pandas.Series。

?
1
2
3
4
5
6
7
print(df['age'])
# Alice    24
# Bob      42
# Name: age, dtype: int64
 
print(type(df['age']))
# <class 'pandas.core.series.Series'>

如果将pandas.Series应用于for循环,则可以按顺序获取值,因此,如果指定pandas.DataFrame列并将其应用于for循环,则可以按顺序获取该列中的值。

?
1
2
3
4
for age in df['age']:
    print(age)
# 24
# 42

如果使用内置函数zip(),则可以一次收集多列值。

?
1
2
3
4
for age, point in zip(df['age'], df['point']):
    print(age, point)
# 24 64
# 42 92

如果要获取索引(行名),使用index属性。如以上示例所示,可以与其他列一起通过zip()获得。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
print(df.index)
# Index(['Alice', 'Bob'], dtype='object')
 
print(type(df.index))
# <class 'pandas.core.indexes.base.Index'>
 
for index in df.index:
    print(index)
# Alice
# Bob
 
for index, state in zip(df.index, df['state']):
    print(index, state)
# Alice NY
# Bob CA

循环更新值

iterrows()方法逐行检索值,返回一个副本,而不是视图,因此更改pandas.Series不会更新原始数据。

?
1
2
3
4
5
6
7
for index, row in df.iterrows():
    row['point'] += row['age']
 
print(df)
#        age state  point
# Alice   24    NY     64
# Bob     42    CA     92

at[]选择并处理原始DataFrame中的数据时更新。

?
1
2
3
4
5
6
7
for index, row in df.iterrows():
    df.at[index, 'point'] += row['age']
 
print(df)
#        age state  point
# Alice   24    NY     88
# Bob     42    CA    134

有关at[]的文章另请参考以下连接。

Pandas获取和修改任意位置的值(at,iat,loc,iloc)

请注意,上面的示例使用at[]只是一个示例,在许多情况下,有必要使用for循环来更新元素或基于现有列添加新列,for循环的编写更加简单快捷。

与上述相同的处理。上面更新的对象被进一步更新。

?
1
2
3
4
5
df['point'] += df['age']
print(df)
#        age state  point
# Alice   24    NY    112
# Bob     42    CA    176

可以添加新列。

?
1
2
3
4
5
df['new'] = df['point'] + df['age'] * 2
print(df)
#        age state  point  new
# Alice   24    NY    112  160
# Bob     42    CA    176  260

除了简单的算术运算之外,NumPy函数还可以应用于列的每个元素。以下是平方根的示例。另外,这里,NumPy的功能可以通过pd.np访问,但是,当然可以单独导入NumPy。

?
1
2
3
4
5
df['age_sqrt'] = pd.np.sqrt(df['age'])
print(df)
#        age state  point  new  age_sqrt
# Alice   24    NY    112  160  4.898979
# Bob     42    CA    176  260  6.480741

 对于字符串,提供了用于直接处理列(系列)的字符串方法。下面是转换为小写并提取第一个字符的示例。

?
1
2
3
4
5
df['state_0'] = df['state'].str.lower().str[0]
print(df)
#        age state  point  new  age_sqrt state_0
# Alice   24    NY    112  160  4.898979       n
# Bob     42    CA    176  260  6.480741       c

到此这篇关于pandas.DataFrame的for循环迭代的实现的文章就介绍到这了,更多相关pandas.DataFrame for循环内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_18351157/article/details/105261636

延伸 · 阅读

精彩推荐
  • PythonPython如何给函数库增加日志功能

    Python如何给函数库增加日志功能

    这篇文章主要介绍了Python如何给函数库增加日志功能,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下...

    David Beazley4212020-08-04
  • PythonPython遍历某目录下的所有文件夹与文件路径

    Python遍历某目录下的所有文件夹与文件路径

    这篇文章主要介绍了Python遍历某目录下的所有文件夹与文件路径 以及输出中文乱码问题的解决方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    yongh7017432021-01-22
  • PythonPython实现将数据框数据写入mongodb及mysql数据库的方法

    Python实现将数据框数据写入mongodb及mysql数据库的方法

    这篇文章主要介绍了Python实现将数据框数据写入mongodb及mysql数据库的方法,结合具体实例形式分析了Python针对mongodb及mysql数据库的连接、写入等操作实现技巧...

    开心果汁8032021-01-26
  • Python详解python读取和输出到txt

    详解python读取和输出到txt

    这篇文章主要介绍了python读取和输出到txt,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小...

    zxfhahaha5462021-06-10
  • PythonPython 闭包的使用方法

    Python 闭包的使用方法

    这篇文章主要介绍了Python 闭包的使用方法的相关资料,了解闭包及定义方法和使用,需要的朋友可以参考下...

    yiibai3222020-12-06
  • PythonPython中暂存上传图片的方法

    Python中暂存上传图片的方法

    这篇文章主要介绍了Python中暂存上传图片的方法,本文使用cStringIO模块实现暂存功能,本文给出简单使用示例,需要的朋友可以参考下 ...

    Python教程网2512019-11-21
  • Pythonpython生成IP段的方法

    python生成IP段的方法

    这篇文章主要介绍了python生成IP段的方法,涉及Python文件读写及随机数操作的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    写代码没钱途6142020-07-20
  • Pythonpython交互界面的退出方法

    python交互界面的退出方法

    今天小编就为大家分享一篇python交互界面的退出方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    Mr-Cat伍可猫10312021-05-28