简体   繁体   中英

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.

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. 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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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