我有一個類似以下但更大的資料框:
import pandas as pd
df = pd.DataFrame({'text': ['Can you open the door?', 'Open the window', 'Call the hair salon.'],'info': ['on', 'on', 'off']})
我想根據資訊列中的內容列印不同的值。例如:
if all values in 'info' == 'on':
print('all values are on')
elif all values in 'info' == 'off':
print('all values are off')
elif 'info' contains both ('on' and 'off'):
print('both values exist')
所以我做了以下事情:
if all(df['info'].unique() == ['on']):
print('all values are on')
elif all(df['info'].unique() == ['off']):
print('all values are off')
elif all(df['info'].unique() == ['off','on']):
print('both values exist')
但我沒有得到任何輸出,我需要一個一致的解決方案,所以如果與我給出的示例不同,所有值實際上只是“開”或“關”,我仍然會得到正確的輸出。
uj5u.com熱心網友回復:
使用sets 比較值,優點是順序不重要,相同的集合是set(['off','on']) == set(['on','off']):
s = set(df['info'])
if s == set(['on']):
print('all values are on')
elif (s == set(['off'])):
print('all values are off')
elif (s == set(['off','on'])):
print('both values exist')
一般解決方案:
s = set(df['info'])
if len(s) == 1:
print(f'all values are {list(s)[0]}')
else:
print(f'multiple values exist - {", ".join(s)}')
uj5u.com熱心網友回復:
要檢查所有值是否都“打開”,您可以使用:
df['info'].eq('on').all()
# False
您還可以使用:
out = df['info'].unique()
if len(out)>1:
print('both values exist')
else:
print(f'all values are {out[0]}')
全部開啟時輸出:
all values are on
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/475006.html
下一篇:未定義檢查變數時if陳述句出錯
