有没有更好的方法来迭代数据帧的每一行



我进行此迭代是为了为数据帧的每个值执行不同的函数:

xxx是一个2-冷数据帧

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

这很好,但我一直想知道是否有办法让相同的操作更可读

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

试试这个:

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)

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

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

您也可以尝试使用lambda函数和类似这样的应用方法:

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

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

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

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

一个潜在的解决方案是对数据帧的列使用map常规functionslambda函数,这比循环(例如df.iterrows()(更快、更高效。

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

  • map仅适用于系列
  • applymap仅适用于DataFrames
  • 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

最新更新