熊猫:根据新创建的列中的上一行创建新列

时间:2020-10-14 19:53:38

标签: python pandas dataframe

我有a two-column numerical dataframe,并且我想添加第三列。

nm1 <- intersect(names(list), dataframe$key)
list[nm1] <- dataframe$label[dataframe$key %in% nm1]

在第一行中 list <- list(fec9 = 'yes', `39c1` = 'no', 'd387' = 'yes', `0065` = 'yes') dataframe <- data.frame(key = c('39c1', 'fec9', 'p731', '0065', 'd387'), label = c('trash', 'wash car', 'cook dinner', 'mow lawn', 'vacuum')) 在其余的行上 Row col1 col2 0 8 8 1 8 4 2 6 2 3 3 7 4 6 4 5 2 6

resulting dataframe应该看起来像这样:

col3 = max(col1 - col2,0)

有有效的方法吗?

2 个答案:

答案 0 :(得分:2)

要创建新列,您可以执行以下操作:

 df['col3'] = 0 # all the rows will be filled with zeros

col3将添加到您的数据框中。

由于第一行的计算方法与其他行不同,因此需要手动进行计算。

df['col3'][0] = max(df['col1'][0] - df['col2'][0], 0)

其他行的计算方法相同,因此可以使用for迭代来实现。

 for row in range(1, len(df)):
        df['col3'][row] = max(df['col1'][row] - df['col2'][row] + df['col3'][row - 1], 0)

P.S:您也可以使用列表理解来完成此操作,也许还为时过早,但是我也会放置代码,以便您可以学习代码。

df['col3'] = 0 # all the rows will be filled with zeros
df['col3'] = [max(df['col1'][row] - df['col2'][row] + df['col3'][row - 1], 0) if row > 0 else max(df['col1'][row] - df['col2'][row], 0) for row in range(len(df))]

这是更Python化的方式,但可能会有些混乱 一见钟情。

答案 1 :(得分:0)

尝试一下:

# Calculate value for first row clip lower value to zero
s = (df.iloc[0, df.columns.get_loc('col1')] - df.iloc[0, df.columns.get_loc('col2')]).clip(0,)

# Calculate difference for each row after first
df['col3'] = (df.iloc[1:, df.columns.get_loc('col1')] - df.iloc[1:, df.columns.get_loc('col2')])

# Fill 'col3' with first value then cumsum differences
df['col3'] = df['col3'].fillna(s).cumsum()

df

输出:

     col1  col2  col3
Row                  
0       8     8   0.0
1       8     4   4.0
2       6     2   8.0
3       3     7   4.0
4       6     4   6.0
5       2     6   2.0