Skip to main content
 首页 » 编程设计

python之打印 DataFrame 的特定行

2024年09月07日7grandyang

我有这个 df:

import pandas as pd 
datas = [{'A':10, 'B':100}, {'A':11,'B':(-210)}, {'A':12,'B':120}, {"A":14, "B":30}] 
df = pd.DataFrame(datas) 
df ["CUMSUM"] = (df["B"].cumsum()) 

我正在尝试获得以下输出:

1) 如果“CUMSUM”列的任何值小于 (-100):仅打印 CUMSUM < (-100) 的第一行,然后停止运行。

2)如果“CUMSUM”列没有任何值低于(-100):只打印最后一行,并停止运行。

谁能帮帮我?

请您参考如下方法:

这可能是你想要的:

import pandas as pd 
 
datas = [{'A':10, 'B':100}, {'A':11,'B':(-210)}, {'A':12,'B':120}, {'A':14, 'B':30}] 
df = pd.DataFrame(datas) 
df['CUMSUM'] = (df['B'].cumsum()) 
 
if (df['CUMSUM'] < -100).any(): 
 
# 1) If the column "CUMSUM" has any value lower than (-100): 
# print just the first row in which CUMSUM < (-100), and stop running. 
 
    print(df.loc[df['CUMSUM'] < -100, :].head(1)) 
 
else: 
 
# 2) If the column "CUMSUM" has not any value lower than (-100): 
# print just the last row, and stop running. 
 
    print(df.loc[df['CUMSUM'] >= -100, :].tail(1))