[英]Looping through pandas dataframe using list comprehension
I'm trying to loop through a pandas dataframe and for every row add a new column called upper
, whose value should be set according to a simple condition based on the values of two other columns of the same row.我正在尝试遍历 Pandas 数据框,并为每一行添加一个名为
upper
的新列,其值应根据基于同一行其他两列的值的简单条件进行设置。
I tried to do that using list comprehension:我尝试使用列表理解来做到这一点:
df['upper'] = [df['Close'][i] if df['Close'][i] > df['Open'][i] else df['Open'][i] for i in df]
But this line of code gives me the following error:但是这行代码给了我以下错误:
raise KeyError(key) from err KeyError: 'Date'
Where Date
is just another column of the dataframe that isn't even involved in that line of code.其中
Date
只是数据框的另一列,甚至不涉及该行代码。 What am i doing wrong here?我在这里做错了什么? Is there a better way to do this?
有一个更好的方法吗? Thanks in advance!
提前致谢!
pandas是一个高级库,循环遍历DataFrame是一种不好的做法
df['upper'] = df[['Close', 'Open']].max(axis=1)
import numpy as np
df['upper'] = np.maximum(df['Close'], df['Open'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.