简体   繁体   English

Pandas:在数据框中创建一个新列,其中的值是从现有列 i 计算出来的。 计算最大值

[英]Pandas: Create a new column in a data frame with values calculated from an already existing column, i. calculate maximum

I want to create a new column with a max values calculation on the first column, as follows:我想在第一列上创建一个具有最大值计算的新列,如下所示:

   High    Highest2P Highest3P  
0 101.0   102.0     103.0  
1 102.0   103.0     109.0  
2 103.0   109.0     109.0      
3 109.0   109.0  
4 100.0 

from pandas import *  

df = pd.DataFrame({  
    "High": pd.Series( [101.0, 102.0, 103.0, 109.0, 100.0] )  
})  

def calcHighest2P(x): return max(df["High"], df["High"].shift(-1))
def calcHighest3P(x): return max(df["High"], df["High"].shift(-1), df["High"].shift(-2))

df["Highest2P"] = calcHighest2P(df["High"])
df["Highest3P"] = calcHighest3P(df["High"])

But I get the following error message: "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."但我收到以下错误消息:“ValueError:系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。”

You can use Rolling.max with assign :您可以将Rolling.maxassign Rolling.max使用:

df.assign(**{
    f'Highest{i}P': pd.Series(df.High.rolling(i).max().dropna().values) 
    for i in range(2, 4)}
)

    High  Highest2P  Highest3P
0  101.0      102.0      103.0
1  102.0      103.0      109.0
2  103.0      109.0      109.0
3  109.0      109.0        NaN
4  100.0        NaN        NaN

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

相关问题 使用 Pandas 从现有列创建新列到数据框 - Create a new column to data frame from existing columns using Pandas 如何从 pandas 数据框的列值创建新行 - How to create a new rows from column values of pandas data frame Pandas:使用从预先存在的列计算的值在数据框中创建两个新列 - Pandas: create two new columns in a dataframe with values calculated from a pre-existing column 基于现有列在 pandas 数据框中创建新列 - Create new columns in pandas data frame based on existing column 根据现有列中的 2 个条件创建新的 pandas 数据框 - Create new pandas data frame based on 2 conditions in an existing column 如何通过从另一列中的句子中提取单词来在 pandas 数据框中创建一个新列? - How can I create a new column in a pandas data frame by extracting words from sentences in another column? 在包含排序组的pandas数据框中创建一个计算列 - Create a calculated column in pandas data frame containing sorted groups 根据其他列值计算出的新的Pandas Dataframe列 - new Pandas Dataframe column calculated from other column values 如何从数据框中选择多列,并在其中我需要在同一代码中使用现有列创建两个新列? - How to select multiple column from a data frame and within that i need to create two new column with existing column in the same code? 如何在 pandas 数据框中创建新列 - How to create a new column in a pandas data frame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM