![](/img/trans.png)
[英]Create new column that is a count of how many entries in a row satisfy a condition for each row of a data frame in pandas
[英]How to add column data to the first row only in pandas OR provide default data for new column entries?
不是確切的代碼,而是簡化了:
df['running_total'] = df.running_total.shift() + df['total']
顯然,在第一個實例中df.running_total.shift()
條目不存在所以它出錯了。
第一個條目有一個特殊的計算,所以我想明確設置它。 或者,只要無法找到上一個行條目或 DNE,就使用該計算作為默認值。
兩種解決方案都可行,更喜歡更快的解決方案(小數據集,不常調用)。
您可以使用:
df = pd.DataFrame({'running_total':[4,5,np.nan, np.nan]})
print (df)
running_total
0 4.0
1 5.0
2 NaN
3 NaN
print (df.running_total.shift())
0 NaN
1 4.0
2 5.0
3 NaN
Name: running_total, dtype: float64
一種可能的解決方案是fillna
- 但它替換了所有NaN
print (df.running_total.shift().fillna(0))
0 0.0
1 4.0
2 5.0
3 0.0
Name: running_total, dtype: float64
如果只想替換第一個值,請通過iat
( iloc
, loc
) 設置它:
shifted = df.running_total.shift()
shifted.iat[0] = 0
print (shifted)
0 0.0
1 4.0
2 5.0
3 NaN
Name: running_total, dtype: float64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.