【问题标题】:Is there a better way to iterate over every row of a dataframe? [duplicate]有没有更好的方法来迭代数据帧的每一行? [复制]
【发布时间】:2021-01-08 19:22:27
【问题描述】:

我正在做这个迭代来为数据帧的每个单个值执行不同的函数:

作为 xxx 一个 2-col 数据帧

for i in range(1, len(xxx)):
row = xxx[i-1:i]
do_something(row['value1'])
do_something_else(row['value2'])

这很好用,但我一直想知道是否有某种方法可以使相同的操作更具可读性

请回答我应该检查的概念或库

【问题讨论】:

  • 这能回答你的问题吗? How to iterate over rows in a DataFrame in Pandas
  • 如果您需要遍历数据框的行,您应该认真质疑数据框是否是数据的最佳表示。几乎所有用途都可以通过某种形式的矢量化更好地解决:将函数应用于数据帧的所有行(即让运行时系统管理您的迭代)。

标签: python pandas dataframe


【解决方案1】:

一种可能的解决方案是对数据框的列使用map 常规functionslambda 函数,这比循环(例如df.iterrows())更快更高效。

这里是基于答案here 的有效数据帧/序列操作方法的总结:

  • map 适用于系列
  • applymap 适用于数据帧
  • apply 适用于 BOTH

` 这是一个玩具示例:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(4, 2), columns=list('AB'))
print(df)

def square(x):
   return x**2

#mapping a lambda function
print('Result of mapping with a lambda function')
df['A'] = df['A'].map(lambda x : x**2)
print(df)

#mapping a regular function
print('Result of mapping with a regular function')
df['C']  =df['A'].map(square)
print(df)

#apply
print('Result of applymap a regular function')
df1 = df.applymap(square)
print(df1)


#apply
print('Result of applying with a regular function')
df2 = df.apply(square)
print(df2)

输出:

          A         B
0 -0.030899 -2.206942
1  0.080991  0.049431
2  1.190754 -0.101161
3  0.794870 -0.969503

Result of mapping with a lambda function
          A         B
0  0.000955 -2.206942
1  0.006560  0.049431
2  1.417894 -0.101161
3  0.631818 -0.969503

Result of mapping with a regular function
          A         B             C
0  0.000955 -2.206942  9.115775e-07
1  0.006560  0.049431  4.302793e-05
2  1.417894 -0.101161  2.010425e+00
3  0.631818 -0.969503  3.991945e-01

Result of applymap with a regular function
              A         B             C
0  9.115775e-07  4.870592  8.309735e-13
1  4.302793e-05  0.002443  1.851403e-09
2  2.010425e+00  0.010234  4.041807e+00
3  3.991945e-01  0.939936  1.593563e-01

Result of applying with a regular function
              A         B             C
0  9.115775e-07  4.870592  8.309735e-13
1  4.302793e-05  0.002443  1.851403e-09
2  2.010425e+00  0.010234  4.041807e+00
3  3.991945e-01  0.939936  1.593563e-01

【讨论】:

    【解决方案2】:

    您也可以尝试使用 lambda 函数和 apply 方法,如下所示:

    假设您有一个函数将元素转换为字符串,然后将该字符串大写。

    def capitalize(cell):
        return str(cell).capitalize()
    

    然后,您可以将该函数应用于所选列的每一行。

    df["Column"].apply(lambda x: capitalize(x))
    

    【讨论】:

      【解决方案3】:

      您可以使用 apply:沿 DataFrame 的轴(行或列)应用函数:

      pandas.DataFrame.apply
      
      DataFrame.apply(func, axis=0, raw=False, result_type=None, args=(), **kwds)
      

      【讨论】:

        【解决方案4】:

        试试这个:

        df=pd.DataFrame([[1,2,3,4],['A','B','C','D']]).T
        df.columns=['A','B']
        def func(X):
            return X**2
        r=map(func, df['A'])
        df['A']=pd.DataFrame(r)
        

        【讨论】:

          猜你喜欢
          • 2020-12-06
          • 1970-01-01
          • 2010-12-27
          • 2021-10-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多