Python 根据另一列中的值创建新列,如果为False,则返回新列的上一个值

Python 根据另一列中的值创建新列,如果为False,则返回新列的上一个值,python,pandas,Python,Pandas,这是一个我已经挣扎了一段时间的问题。假设我有一个简单的数据帧df,其中df['a']=[1,2,3,1,4,6]和df['b']=[10,20,30,40,50,60]。我想创建第三列“c”,其中如果df['a']==1,df['c']=df['b']。如果为false,则df['c']=df['c']的上一个值。我曾尝试使用np.where实现这一点,但结果并不是我所期望的。有什么建议吗 df = pd.DataFrame() df['a'] = [1,2,3,1,4,6] df['b'] =

这是一个我已经挣扎了一段时间的问题。假设我有一个简单的数据帧df,其中df['a']=[1,2,3,1,4,6]和df['b']=[10,20,30,40,50,60]。我想创建第三列“c”,其中如果df['a']==1,df['c']=df['b']。如果为false,则df['c']=df['c']的上一个值。我曾尝试使用np.where实现这一点,但结果并不是我所期望的。有什么建议吗

df = pd.DataFrame()
df['a'] = [1,2,3,1,4,6]
df['b'] = [10,20,30,40,50,60]
df['c'] = np.nan
df['c'] = np.where(df['a'] == 1, df['b'], df['c'].shift(1))
结果是:

   a   b     c
0  1  10  10.0
1  2  20   NaN
2  3  30   NaN
3  1  40  40.0
4  4  50   NaN
5  6  60   NaN
鉴于我本应预期:

   a   b     c
0  1  10  10.0
1  2  20  10.0
2  3  30  10.0
3  1  40  40.0
4  4  50  40.0
5  6  60  40.0
试试这个:

df.c.ffill(inplace=True)
输出:

   a   b     c
0  1  10  10.0
1  2  20  10.0
2  3  30  10.0
3  1  40  40.0
4  4  50  40.0
5  6  60  40.0
试试这个:

df.c.ffill(inplace=True)
输出:

   a   b     c
0  1  10  10.0
1  2  20  10.0
2  3  30  10.0
3  1  40  40.0
4  4  50  40.0
5  6  60  40.0

因为你的
df['c']
都是
np.nan
df['c'].shift(1)
np.where中总是
np.nan
。那么,作为np.where应该取df['c']的前一个值,因为第一个值是10,下一个值也应该是10,所以这种行为很奇怪。不,
np.其中
行为是正确的。否。何处可在当前状态下工作
df['c']
。其中所有值均为
np.nan
。当它从一行移动到另一行时,它不会考虑每一行的更新值。因为你的
df['c']
都是
np.nan
df['c'].shift(1)
np.where
中总是
np.nan
。那么,作为np.where应该取df['c']的先前值,因为第一个值是10,下一个值也应该是10,所以这个行为是奇怪的。不,
np。其中
行为是正确的。否。何处可在当前状态下工作
df['c']
。其中所有值均为
np.nan
。当它从一行移动到另一行时,不会考虑每一行及其更新的值。