pandas中列的条件值

时间:2018-01-05 19:59:17

标签: python pandas

我试图做这样的事情:

d={'Month':['January','February','March','April'], 'Saves':[2000, 2100, 1900, 1500]}
saves=pd.DataFrame(data=d)

并且像这样:

    Month       Saves
0   January     2000
1   February    2100
2   March       1900
3   April       1500

我想要的是创建一个新专栏' Spent'逻辑:如果上个月的价值更高 - >"是",否则 - > '否',如:

    Month       Saves    Spent
0   January     2000       -
1   February    2100      No
2   March       1900      Yes
3   April       1500      Yes

我不知道该怎么做,尝试以多种方式迭代,但它没有用。

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用shift访问下一栏

saves['Spent'] = np.where(saves['Saves'] < saves['Saves'].shift(), 'Yes', 'No')


    Month       Saves   Spent
0   January     2000    No
1   February    2100    No
2   March       1900    Yes
3   April       1500    Yes

答案 1 :(得分:2)

注意,这里第一行需要区别对待

saves.at[1:,'Spent']=saves.Saves.diff().gt(0).map({True:'No',False:'Yes'}).iloc[1:]
saves
Out[190]: 
      Month  Saves Spent
0   January   2000   NaN
1  February   2100    No
2     March   1900   Yes
3     April   1500   Yes
saves.fillna('')
Out[191]: 
      Month  Saves Spent
0   January   2000      
1  February   2100    No
2     March   1900   Yes
3     April   1500   Yes