遍历一列并填充fucntion Pandas Dataframe Python中的行 [英] Loop over one column and fill rows in fucntion Pandas Dataframe Python
问题描述
我正在尝试遍历数据框.尤其是通过date列,这意味着对于每个日期,我都会获取该日期的x,y和z值并将其填充到我定义的函数中.我不知该如何正确地称呼它.我的代码如下所示:
I am trying to loop over a dataframe. Especially through the date column so means for every date I get the x, y and z values for that date and fill it into my defined function. Somehow I am not sure how i can properly call it. My code looks like the following:
import pandas as pd
def calc_funct(x, y, z):
func = x*y*z
return func
if __name__ == '__main__':
df = pd.read_csv('C:/Data.csv')
for column in df:
results = calc_funct(df['x'], df['y'], df['z'])
print(result)
输入内容如下:
date x y z
0 2017-11-11 18 17 7
1 2017-11-11 16 19 3
2 2017-11-11 13 14 2
3 2017-11-11 12 13 1
4 2017-11-11 11 12 9
5 2017-11-11 10 11 10
6 2017-11-11 21 10 11
7 2017-11-12 13 19 12
8 2017-11-13 18 17 12
9 2017-11-14 9 10 20
10 2017-11-15 2 20 13
11 2017-11-18 13 13 9
12 2017-11-19 18 14 16
13 2017-11-20 14 11 19
14 2017-11-21 18 15 19
对于日期2017-11-11,我将计算值(例如,将当天的所有值相加/相减)并进行存储(例如在列表中.然后遍历下一个日期2017-11-12等...
For date 2017-11-11 I would calculate the values (e.g. add/subtract all values them at that date) and store it e.g. in a list. Then iterate over the next date 2017-11-12 etc...
推荐答案
如果您希望所有列+函数产生的新列,您可以这样做:
If you want all the columns + the new column which is the result of your function, you can do so:
df['result'] = calc_funct(df['x'], df['y'], df['z'])
或仅date
和result
以及另一行代码:
or just date
and result
with this other line of code:
df = df[['date','result']]
编辑
result = []
for index, row in df.iterrows():
result.append(row['date'])
result.append(calc_funct(row['x'], row['y'], row['z']))
print result
这篇关于遍历一列并填充fucntion Pandas Dataframe Python中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!