有没有更好的方法可以遍历数据帧的每一行?

时间:2020-09-22 16:07:41

标签: python pandas dataframe

我正在执行此迭代以对数据帧的每个单个值执行不同的功能:

成为2列数据框xxx

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

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

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

4 个答案:

答案 0 :(得分:2)

尝试一下:

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)

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

您也可以尝试使用lambda函数以及类似的apply方法:

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

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

然后您可以将该功能应用于所选列的每一行。

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

答案 3 :(得分:1)

一种可能的解决方案是将map常规functionslambda函数应用于数据帧的列,这比循环(例如df.iterrows() )。

以下是基于答案here的有效数据框/系列操作方法的摘要:

  • map适用于系列
  • applymap适用于
  • 数据框
  • apply适用于两者

`这是一个玩具示例:

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