我正在嘗試if用 Python撰寫一個陳述句來遍歷 DataFrame 的行。如果該行滿足多個可能條件之一,則會進行計算。我的 MWE 是:
import numpy as np
import pandas as pd
coin = ['a','b','c'] # conditions
xlist = pd.DataFrame() # data
xlist['col1'] = np.array(['a','j','k','b','b','d','c','a']) # state
xlist['col2'] = np.array([1,2,2,1,2,0,1,3])
for ii in range(len(xlist)):
if any(coin in xlist['col1'][ii]):
# if state meets a condition, do calculation x
print('result 1')
else:
# if state doesn't meet condition, do calculation y
print('result 2')
我不斷收到錯誤訊息:
TypeError: 'in <string>' requires string as left operand, not list
所以這不是正確的 Python 方式。我在any宣告中做錯了什么?
輸出應該是:
result 1
result 2
result 2
result 1
result 1
result 2
result 1
result 1
uj5u.com熱心網友回復:
使用np.where有Series.isin:
In [846]: l = np.where(xlist['col1'].isin(coin), 'result 1', 'result 2')
In [847]: l # numpy array
Out[847]:
array(['result 1', 'result 2', 'result 2', 'result 1', 'result 1',
'result 2', 'result 1', 'result 1'], dtype='<U8')
In [848]: l.tolist() # list
Out[848]:
['result 1',
'result 2',
'result 2',
'result 1',
'result 1',
'result 2',
'result 1',
'result 1']
uj5u.com熱心網友回復:
我認為你的條件是錯誤的。而不是any(coin in xlist['col1'][ii]),嘗試xlist['col1'][ii] in coin:
for ii in range(len(xlist)):
if xlist['col1'][ii] in coin:
# if state meets a condition, do calculation x
print('result 1')
else:
# if state doesn't meet condition, do calculation y
print('result 2')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/362531.html
下一篇:熊貓分組布爾列值之間的所有行
