简体   繁体   English

如何在 pandas 中的 dataframe 上使用 function?

[英]How to use a function on a dataframe in pandas?

I am having an issue with applying a function to my dataframe.我在将 function 应用到我的 dataframe 时遇到问题。 Simply put, I just need to make the l column increase by a factor of 1.07 each row.简单地说,我只需要将 l 列每行增加 1.07 倍。 The math would look like:数学看起来像:

l[0]
l[0] * 1.07 = l[1]
l[1] * 1.07 = l[2] 

It shouldn't be that hard, but I can't figure it out.这不应该那么难,但我无法弄清楚。 Any help is appreciated!任何帮助表示赞赏!

a = 1.1
k = 3
l = 4
years = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
df = pd.DataFrame({'a' : a,
                   'l' : l,
                   'k' : k,
                   'y' :  a * (k ** (1/3)) * (l ** (2/3)),
                   'period' : years
                  })

df

Assuming you want to reassign it to your dataframe:假设您要将其重新分配给您的 dataframe:

import pandas as pd 
import numpy as np 

a = 1.1
k = 3
l = 4
years = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
df = pd.DataFrame({'a' : a,
                   'l' : l,
                   'k' : k,
                   'y' :  a * (k ** (1/3)) * (l ** (2/3)),
                   'period' : years
                  })
result = pd.Series([l * 1.07**i for i in range(2)])
df.l = result 
print(df)

The key code here is这里的关键代码是

[l * 1.07**i for i in range(2)]

which is called a list comprehension, and it says generate a list of 2 elements where the i th element is 1.07**i * l .这称为列表推导,它说生成一个包含 2 个元素的列表,其中第i个元素是1.07**i * l The pd.Series allows you to add the result to your dataframe (you can omit it if you set the range to 10 specifically because 10 is the number of rows in your dataframe). pd.Series允许您将结果添加到 dataframe (如果您将范围设置为 10,则可以省略它,因为 10 是数据框中的行数)。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM