iT邦幫忙

0

大大門求助,基本python 問題

  • 分享至 

  • xImage

大大們 :
如下語法會是哪邊有問題,能否幫忙
謝謝
import pandas as pd
A = pd.read_excel('國文成績.xlsx')
print(A)
print('-'*100)
if A['國文成績'] >= 90 :
A['level'] = 'Good'
else :
A['level'] = 'Fail'

出現如下ValueError
name 學號 國文成績
0 Jack 1 95
1 Kay 2 51
2 Mary 3 61
3 Alice 4 28
4 Say 5 72
5 Sala 6 84
6 Eddie 7 92
7 SL 8 30
8 Mark 9 28
9 CY 10 84
10 Nick 11 91


ValueError Traceback (most recent call last)
in
3 print(A)
4 print('-'*100)
----> 5 if A['國文成績'] >= 90 :
6 A['level'] = 'Good'
7 else :

~\anaconda3\lib\site-packages\pandas\core\generic.py in nonzero(self)
1440 @final
1441 def nonzero(self):
-> 1442 raise ValueError(
1443 f"The truth value of a {type(self).name} is ambiguous. "
1444 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

ifurther iT邦新手 4 級 ‧ 2022-12-04 21:12:20 檢舉
請問A.columns的結果
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
re.Zero
iT邦研究生 5 級 ‧ 2022-12-04 22:55:41
最佳解答

我認為這不算 「Python 基本」,畢竟都引入 pandas 了……

## Python==3.10.8; pandas==1.5.2;
import pandas as pd
A = pd.read_excel('國文成績.xlsx')
print(A)
print('-'*100)
A['level'] = A['國文成績'].apply(lambda x: 'Good' if x >= 90 else 'Fail')
print(A)
1
alien663
iT邦研究生 5 級 ‧ 2022-12-05 08:52:49

類似問題可以先google看看,通常可以直接找到解答。
你這問題是因為 A['國文成績'] >= 90 的回傳結果不是true或是false,所以if無法判斷結果,才報錯的。
如果要解決問題,可以先試著print(A['學號 '], A['國文成績'] >= 90)看看中間哪一筆資料怪怪的,把有問題的部分直接顯示出來,再根據狀況去排除。

參考文章 : ValueError: The truth value of a series is ambiguous. use a.empty, a.bool(), a.item(), a.any() or a.all()

我要發表回答

立即登入回答