Pandas DataFrame如何根據(jù)上一行值條件累加生成新列?

利用pandas高效累加生成dataframe新列

本文介紹如何使用python的Pandas庫,根據(jù)DataFrame中現(xiàn)有列的值,創(chuàng)建一個新的列,并基于特定條件進(jìn)行累加計數(shù)。 我們將以一個包含’col1’、’col2’、’col3’三列的DataFrame為例,創(chuàng)建一個新的’col4’列。當(dāng)’col1’列的值介于3和5之間(不包含3和5)時,’col4’列的值累加計數(shù);否則為0。

Pandas DataFrame如何根據(jù)上一行值條件累加生成新列?

直接使用df.apply和Lambda函數(shù)雖然可以判斷條件,但難以實現(xiàn)累加。 更有效的方法是結(jié)合np.where、cumsum()和fillna()函數(shù)。 np.where根據(jù)條件生成一個包含1(滿足條件)和NaN(不滿足條件)的Series;cumsum()對該Series進(jìn)行累加;fillna(0)將NaN替換為0。 這種方法簡潔高效。

代碼示例:

import pandas as pd import numpy as np  # 示例DataFrame (請?zhí)鎿Q為您的實際數(shù)據(jù)) data = {'col1': [1, 4, 2, 4.5, 6, 4, 3.5],          'col2': [10, 20, 30, 40, 50, 60, 70],          'col3': [100, 200, 300, 400, 500, 600, 700]} df = pd.DataFrame(data)  df['col4'] = pd.Series(np.where((df['col1'] > 3) & (df['col1'] < 5), 1, np.nan)).cumsum().fillna(0)  print(df)

雖然循環(huán)迭代或自定義函數(shù)結(jié)合df.apply也能實現(xiàn),但效率較低且代碼冗余。 因此,推薦使用np.where、cumsum()和fillna()的組合,因為它簡潔、高效且易于理解。 此方法可輕松根據(jù)上一行值條件在Pandas DataFrame中新增列并進(jìn)行累加計數(shù)。

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點贊8 分享