简体   繁体   English

如何使用单列作为参数将函数应用于数据框中的多列?

[英]How can I apply a function to many columns in a dataframe using a single column as an argument?

I have a dataframe with 100+ columns I need to apply a function to, but I can't figure out how to pass the first column as an argument.我有一个包含 100 多列的数据框,我需要对其应用函数,但我不知道如何将第一列作为参数传递。

For example, if my table is:例如,如果我的表是:

df = pd.DataFrame({'argument':[1,2,0.5],
                   'day1':[4,5,6],
                   'day2':[5,1,2]})

   argument day1 day2 day3...
0  1.0      4    5
1  2.0      5    1
2  0.5      6    2

And I have a function like this (mine is much more complicated, this is just for the example):我有一个这样的函数(我的要复杂得多,这只是为了举例):

def function (i,j):
    return i * j

I would like my output to be:我希望我的输出是:

   argument day1 day2 day3...
0  1.0      4    5
1  2.0      10   2
2  0.5      3    1

This is getting me very strange results, does anyone know what I'm doing wrong?这让我得到了非常奇怪的结果,有谁知道我做错了什么? Thank you!谢谢!

def function (i,j):
    return i- j
df = df.apply(function, axis=1, j=df['argument'])

First, you have the wrong direction for your axis, it should be set to be 0 instead of 1.首先,您的轴方向错误,应将其设置为 0 而不是 1。

Second, if you apply your function like that, it will apply the function to your argument column.其次,如果您像这样应用您的函数,它将将该函数应用于您的参数列。 And it won't be the same as what you wanted there.它不会和你想要的一样。

So, change your code become like this所以,改变你的代码变成这样

import pandas as pd

def function (i,j):
    return i * j

df = pd.DataFrame({'argument':[1,2,0.5],
                   'day1':[4,5,6],
                   'day2':[5,1,2]})

df2 = df.iloc[:,-2:].apply(function,axis=0,j=df['argument'])
df.iloc[:,-2:] = df2
print(df)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 function 应用于 dataframe 将列作为参数传递 - How to apply function to a dataframe passing a column as an argument 如何使用多行和多列作为输入在DataFrame列上应用函数? - How to apply a function on a DataFrame Column using multiple rows and columns as input? 如何将 apply() function 用于单个列? - How can I use the apply() function for a single column? Pandas dataframe,如何按单列分组并将总和应用于多列并添加新的总和列? - Pandas dataframe, how can I group by single column and apply sum to multiple column and add new sum column? 如何使用numpy和python将函数应用于矩阵的一行或一列 - How can I apply a function to a single row or column of a matrix using numpy and python 如何在不使用多个 OR 的情况下将单个条件应用于数据框中的列列表并将值添加到第 4 列 - How to apply single condition to a list of columns in a dataframe and add value to 4th column without using multiple OR's Pandas dataframe,如何按多列分组并为特定列应用总和并添加新的计数列? - Pandas dataframe, how can I group by multiple columns and apply sum for specific column and add new count column? 在数据框中的其他列上使用应用函数的新列 - New column using apply function on other columns in dataframe 如何在数据框列上应用上限? - How can I apply ceiling on a dataframe column? python-将dataframe列作为apply函数中的参数传递 - python - pass dataframe column as argument in apply function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM