使用列和行作为参数遍历整个 Pandas 数据框
Iterating through entire Pandas Dataframe using column and row as arguments
我有这个空的 pandas 数据框和一个函数值 (x,y),它接受 2 个参数,即 pandas 数据框中点的行号和列号。我想知道是否有一种更简单的方法可以使用这些参数遍历整个空数据框,也许使用 df.apply。
我知道可以遍历每个单独的列和 运行 df.apply 在单独的列上,但是是否可以在没有 运行 任何循环或什么的情况下做到这一点永远如此。
本质上,我正在寻找这样的东西,我可以在整个数据帧上运行
df_copy.apply(lambda x: myfunction(x.value, x.column))
然而,x.column不存在,所以有另一种方法可以做到,或者我做错了什么
谢谢!
是,使用系列的 name
和 index
属性:
df = pd.DataFrame(1, index = np.arange(10,51,10), columns = np.arange(5))
显示输入数据框
0 1 2 3 4
10 1 1 1 1 1
20 1 1 1 1 1
30 1 1 1 1 1
40 1 1 1 1 1
50 1 1 1 1 1
让我们定义自定义函数并使用行作为列来进行计算。
def f(x):
#add row values to column values
return x.name + x.index
df.apply(f)
输出:
0 1 2 3 4
10 10 11 12 13 14
20 20 21 22 23 24
30 30 31 32 33 34
40 40 41 42 43 44
50 50 51 52 53 54
注意:apply
将数据帧的每一列(这是一个 pd.Series)传递给函数 f。每个系列都有一个属性 name
是列标题,index
是数据帧行索引。因此,函数 f returns 为数据帧的每一列计算 pd.Series 并作为数据帧放回原处。
在评论中回答问题,让我们使用字符串:
df = pd.DataFrame(1, index=['Ted','Bill','Ralph','John','Tim'], columns=['A','B','C','D','E'])
def f(x):
#Concatenate row values with column values
return x.index + '_' + x.name
df.apply(f)
或使用 lambda 函数
df.apply(lambda x: x.index + '_' + x.name)
输出:
A B C D E
Ted Ted_A Ted_B Ted_C Ted_D Ted_E
Bill Bill_A Bill_B Bill_C Bill_D Bill_E
Ralph Ralph_A Ralph_B Ralph_C Ralph_D Ralph_E
John John_A John_B John_C John_D John_E
Tim Tim_A Tim_B Tim_C Tim_D Tim_E
我有这个空的 pandas 数据框和一个函数值 (x,y),它接受 2 个参数,即 pandas 数据框中点的行号和列号。我想知道是否有一种更简单的方法可以使用这些参数遍历整个空数据框,也许使用 df.apply。
我知道可以遍历每个单独的列和 运行 df.apply 在单独的列上,但是是否可以在没有 运行 任何循环或什么的情况下做到这一点永远如此。
本质上,我正在寻找这样的东西,我可以在整个数据帧上运行
df_copy.apply(lambda x: myfunction(x.value, x.column))
然而,x.column不存在,所以有另一种方法可以做到,或者我做错了什么
谢谢!
是,使用系列的 name
和 index
属性:
df = pd.DataFrame(1, index = np.arange(10,51,10), columns = np.arange(5))
显示输入数据框
0 1 2 3 4
10 1 1 1 1 1
20 1 1 1 1 1
30 1 1 1 1 1
40 1 1 1 1 1
50 1 1 1 1 1
让我们定义自定义函数并使用行作为列来进行计算。
def f(x):
#add row values to column values
return x.name + x.index
df.apply(f)
输出:
0 1 2 3 4
10 10 11 12 13 14
20 20 21 22 23 24
30 30 31 32 33 34
40 40 41 42 43 44
50 50 51 52 53 54
注意:apply
将数据帧的每一列(这是一个 pd.Series)传递给函数 f。每个系列都有一个属性 name
是列标题,index
是数据帧行索引。因此,函数 f returns 为数据帧的每一列计算 pd.Series 并作为数据帧放回原处。
在评论中回答问题,让我们使用字符串:
df = pd.DataFrame(1, index=['Ted','Bill','Ralph','John','Tim'], columns=['A','B','C','D','E'])
def f(x):
#Concatenate row values with column values
return x.index + '_' + x.name
df.apply(f)
或使用 lambda 函数
df.apply(lambda x: x.index + '_' + x.name)
输出:
A B C D E
Ted Ted_A Ted_B Ted_C Ted_D Ted_E
Bill Bill_A Bill_B Bill_C Bill_D Bill_E
Ralph Ralph_A Ralph_B Ralph_C Ralph_D Ralph_E
John John_A John_B John_C John_D John_E
Tim Tim_A Tim_B Tim_C Tim_D Tim_E