我正在嘗試根據資料框中的值形成列印陳述句。期望的結果是宣告,例如;
'有值的日期是 Jan3, Jan4'
我的df的一個例子如下;
| 價值 | |
|---|---|
| 1月2日 | 0.0 |
| 1月3日 | 0.5 |
| 1月4日 | 0.5 |
我嘗試的是;
DaysWithValue = [] #an empty list
if df['Value'] > 0:
DaysWithValue.append(df['Value'].index]
print('the days with value are;' ' ' DaysWithValue)
問題是我收到錯誤訊息;
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
a.___() 沒有一個起作用,我希望它對每一行都起作用,而不是為了一個整體的事實。
即使 IF 陳述句有效,我也不確定 print 陳述句是否可以將串列作為它的非字串使用。
關于實作這一目標的更簡單方法的任何建議?
uj5u.com熱心網友回復:
import pandas as pd
df = pd.DataFrame({"date": ['Jan 2', 'Jan 3', 'Jan 4'], "value": [0, 0.5, 0.4]})
dates_with_values = df[df['value'] > 0]['date'].tolist()
print(f"The dates with values: {', '.join(dates_with_values)}.")
輸出:
The dates with values: Jan 3, Jan 4.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/460389.html
上一篇:如何從檔案中批量恢復特定字串
