![](/img/trans.png)
[英]Pandas: Copy a value in a dataframe to multiple rows based on a condition
[英]set value in multiple rows in pandas dataframe based on condition
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”中的“ 0.0406”值填充為“ 1”,且不低於0.04。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.