Python pandas 按行、按列遍历DataFrame

在对DataFrame数据进行处理时,存在需要对数据内容进行遍历的场景。因此记录一下按照行,列遍历的几种方式。

1. 使用loc或iloc方法

  • loc:表示location,填写内容为行的值或者列表,若填写内容为值,则返回对应行的内容(Series类型);若填写内容为列表,则返回对应行的内容(DataFrame类型)
  • iloc:表示integer+location,填写内容为行的索引(int类型)或者列表,返回内容与loc相同。

因此若需要按照行进行遍历时,

2. 使用iterrows()方法

  • iterrows():按行遍历,将DataFrame的每一行迭代为(index, Series)对,可以通过row[name]对元素进行访问

因此可以直接使用iterrows()方法,获取得到行内容

代码如下:

data = {'a': {'x': [1, 1], 'y': [2, 1], 'z': [3, 1]},
        'b': {'x': [1, 2], 'y': [2, 2], 'z': [3, 2]},
        'c': {'x': [1, 3], 'y': [2, 3], 'z': [3, 3]}}
data_pd = pd.DataFrame(data)

print(data_pd)

for row in data_pd.index:
    print(data_pd.loc[row]['a'])

for row_id in range(data_pd.shape[0]):
    print(data_pd.iloc[row_id]['a'])

for index, row in data_pd.iterrows():
    print(row['a'])

运行结果,三种方法结果相同:

        a       b       c
x  [1, 1]  [1, 2]  [1, 3]
y  [2, 1]  [2, 2]  [2, 3]
z  [3, 1]  [3, 2]  [3, 3]

[1, 1]
[2, 1]
[3, 1]

1. 使用列索引方式

DataFrame可以直接使用[列名称]的方式获取列的值,即 data_pd['a']即可得到列内容。

因此若需要按照列进行遍历时,

2. 使用iteritems()方法

  • iteritems():按列遍历,将DataFrame的每一列迭代为(列名, Series)对,可以通过row[index]对元素进行访问

因此可以直接使用iteritems()方法,获取得到列内容

代码如下:

data = {'a': {'x': [1, 1], 'y': [2, 1], 'z': [3, 1]},
        'b': {'x': [1, 2], 'y': [2, 2], 'z': [3, 2]},
        'c': {'x': [1, 3], 'y': [2, 3], 'z': [3, 3]}}
data_pd = pd.DataFrame(data)

print(data_pd)

for col in data_pd.columns:
    print(data_pd[col].iloc[0])

for index, col in data_pd.iteritems():
    print(col.iloc[0])

运行结果,两种方法结果相同:

        a       b       c
x  [1, 1]  [1, 2]  [1, 3]
y  [2, 1]  [2, 2]  [2, 3]
z  [3, 1]  [3, 2]  [3, 3]

[1, 1]
[1, 2]
[1, 3]

Original: https://blog.csdn.net/weixin_43115411/article/details/126030711
Author: 琲世
Title: Python pandas 按行、按列遍历DataFrame

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/674341/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球