[英]In Pandas, how do I apply a function to a row of a dataframe, where each item in the row should be passed to the function as an argument?
[英]How can I apply a function to each row in a pandas dataframe?
我对编码很陌生,所以这可能很简单,但到目前为止我找到的答案都没有以我能理解的方式提供信息。
我想获取一列数据并应用 function (axe^bx),其中 a > 0 和 b < 0。在这种情况下,(x) 将是我数据每一行中的浮点值。
看看我到目前为止有什么,但我不确定 go 从这里到哪里......
def plot_data():
# read the file
data = pd.read_excel(FILENAME)
# convert to pandas dataframe
df = pd.DataFrame(data, columns=['FP Signal'])
# add a blank column to store the normalized data
headers = ['FP Signal', 'Normalized']
df = df.reindex(columns=headers)
df.plot(subplots=True, layout=(1, 2))
df['Normalized'] = df.apply(normalize(['FP Signal']), axis=1)
print(df['Normalized'])
# show the plot
plt.show()
# normalization formula (exponential) = a x e ^bx where a > 0, b < 0
def normalize(x):
x = A * E ** (B * x)
return x
我可以显示此图像,但不能显示“标准化”数据...
谢谢你的帮助!
您的代码几乎是正确的。
# normalization formula (exponential) = a x e ^bx where a > 0, b < 0
def normalize(x):
x = A * E ** (B * x)
return x
def plot_data():
# read the file
data = pd.read_excel(FILENAME)
# convert to pandas dataframe
df = pd.DataFrame(data, columns=['FP Signal'])
# add a blank column to store the normalized data
headers = ['FP Signal', 'Normalized']
df = df.reindex(columns=headers)
df['Normalized'] = df['FP Signal'].apply(lambda x: normalize(x))
print(df['Normalized'])
df.plot(subplots=True, layout=(1, 2))
# show the plot
plt.show()
我将apply
行更改为以下内容: df['FP Signal'].apply(lambda x: normalize(x))
。 它只需要 df['FP Signal'] 上的值,因为您不需要整行。 lambda x
表示分配给 x 的当前值,我们将其发送以进行标准化。
你也可以写df['FP Signal'].apply(normalize)
更直接更简单。 使用 lambda 只是我个人的偏好,但很多人可能不同意。
一个小的补充是在更改 dataframe 之后放置df.plot(subplots=True, layout=(1, 2))
。 如果您在更改 dataframe 之前 plot,您将看不到 plot 的任何更改。 df.plot
实际上在做 plot, plt.show
只是显示它。 这就是为什么df.plot
必须在您处理完数据之后。
您可以使用map
将 function 应用于字段
s = pd.Series(['cat', 'dog', 'rabbit'])
s.map(lambda x: x.upper())
0 CAT
1 DOG
2 RABBIT
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.