if-else 逻辑来设置数据框列的值

If-else logic to set value of dataframe column

我在数据框中有数据 (df) 类似于下面的结构

ID Sessions
1234 400
5678 200
9101112 199
13141516 0

我想在数据框中创建一个新列 (new_col),根据会话值对每个示例进行排名,但我想确保 rank/zeroed 中不考虑 0 个会话。

我尝试应用下面的 lambda,但这不正确:

df['new_col'] = df['Sessions'].apply(lambda x: 0 if x == 0 else df['Sessions'].rank(ascending=True, pct=True))

采样所需的输出

ID Sessions new_col
1234 400 1.000000
5678 200 0.999987
9101112 199 0.999974
13141516 0 0

像这样的? :

df['new_col'] = df.loc[df.Sessions > 0, 'Sessions'].rank(ascending=True, pct=True)

df['new_col'] = df['Sessions'].replace(0, np.NaN).rank(pct=True,).fillna(0)

如果你想要一个安全的切片,assign 是你的朋友。试试这个。

df.assign(newcol=lambda d: (
    d["Sessions"] # grab the series
    .replace(0, np.NaN) # replace the 0s with NaNs
    .rank(pct=True, ) # rank as percentages
    .fillna(0) # fill zeros back in.
   )
)

此外,这样您就可以将这个管道整齐地包装在一个函数中。