Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 表中列的条件值_Python_Pandas - Fatal编程技术网

Python 表中列的条件值

Python 表中列的条件值,python,pandas,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 然后变成这样: d={'Month':[

我正在尝试这样做:

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
然后变成这样:

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
我想创建一个新的列'spend',其逻辑如下:如果上个月的值大于->是,否则->否,如:

    Month       Saves    Spent
0   January     2000       -
1   February    2100      No
2   March       1900      Yes
3   April       1500      Yes
我不知道该怎么做,尝试了很多方法进行迭代,但都没有成功


谢谢

您可以使用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
保存['saved']=np.where(保存['saves']
注意,这里第一行需要区别对待

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

哦,天哪,太谢谢你了,我正要刮我的桌子。很简单,谢谢!如果你想处理第一排,一定要看一下@Wen的答案谢谢你这么快的回答,我已经听了差不多一个小时了!非常感谢你@YelasuHaldYW~你可以考虑接受和赞成你喜欢的答案。