python - 根据条件在 Pandas 数据框中的多行中设置值

标签 python pandas

   temperature  precipitation
0         1.26         0.0279
1         1.64         0.0330
2         1.98         0.0381
3         2.31         0.0406
4         2.61         0.0406
5         2.89         0.0381
6         3.15         0.0356
7         3.51         0.0305
8         3.78         0.0305
9         3.78         0.0305

在上面的数据框中,我想创建一个新列 C precipitation 之后的 4 行值为 1小于 0.04 当且仅当 precipitation在这 4 行中小于 0.04。我尝试使用 pd.where但这只会设置当前行的值。

预期输出:

enter image description here

最佳答案

IIUC,以下;

创建“C”列并填充nan:

df['C'] = np.nan

在“C_”列中计算“降水”< 0.04 的连续出现次数:

def rolling_count(val):
    if val < 0.04:
        rolling_count.count +=1
    else:
        rolling_count.count = 0
    return rolling_count.count
rolling_count.count = 0

df['C_'] = df['precipitation'].apply(rolling_count)

用“1”填充“C”列,找到第一个“4”并向后填充其他 3 个:

df.loc[df[df['C_'] == 4].head(1).index.item(), 'C'] = 1
df['C'] = df['C'].fillna(method = 'bfill', limit = 3)
df['C'] = df['C'].fillna(0)
df['C'] = df['C'].astype(int)

df

   temperature  precipitation  C  C_
0         1.26         0.0279  0   1
1         1.64         0.0330  0   2
2         1.98         0.0381  0   3
3         2.31         0.0406  0   0
4         2.61         0.0406  0   0
5         2.89         0.0381  1   1
6         3.15         0.0356  1   2
7         3.51         0.0305  1   3
8         3.78         0.0305  1   4
9         3.78         0.0305  0   5

注意;此结果与您的示例显示的结果不同,但 IIUC 您需要找到低于 0.04 的 4 个连续行并填充“C”。问题是您在“C”中填充了“1”的“0.0406”值不低于 0.04。

关于python - 根据条件在 Pandas 数据框中的多行中设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53621888/

相关文章:

python - 如何将 QuTip 添加到 canopy?因为试了很多次,每次都报错。

python - 使用 pandas 创建多图 block 多系列散点图

python / Pandas : Using built-in functions as arguments in user-defined function

python-3.x - 如何在此 DataFrame 上应用函数以将日期更改为所需格式并避免 '0' 和 '-'

python - Pandas datetime64 到字符串

python - 将文本特征名称链接到其 tfidf 值

Python Selenium WebDriver Chrome click() 不起作用

python - 将 matplotlib 图传递给 HTML( flask )

python - django python 排序错误

python - Pandas 数据框多行查询