我對 Pandas、python 和 google colab 非常陌生,我剛剛花了 6 個多小時試圖找到一種方法來做一個我在 2 分鐘內在 google 表格中完成的公式。
我想將 if 陳述句的結果連接到一個列中,就像我在“Things to fix”列中所做的那樣,如果列中有“Yes”,問題就會出現,以便作業人員可以檢查需要做什么。

在 excel 和作業表中,我都可以使用“&”來連接 if 陳述句,但是每當我嘗試使用 Pandas 連接時,都會彈出某種錯誤。我也嘗試使用這種格式的代碼:
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
# Output = 'a,b,c,d'
但它有點改變了資料并把一切都搞砸了。
我在 google colab 環境中作業,處理 .ipynb 檔案。
非常感謝您的關注和幫助。
uj5u.com熱心網友回復:
為什么不是這個?
df['tofix'] = df.apply(lambda r: ','.join([r.key*'key',r.win*'win',r.eng*'eng'])
uj5u.com熱心網友回復:
使用melt:
out = df.melt(id_vars=['Car Id'], var_name='Things to fix', ignore_index=False) \
.query("value == 'Yes'").groupby('Car Id')['Things to fix'] \
.apply(lambda x: ','.join(x.str.extract(r'(\w )\?', expand=False)))
out = df.merge(out, on='Car Id', how='left')
輸出:
>>> out
Car Id Problem with Key? Problem with windows? Problem in the engine? Things to fix
0 1000 Yes Yes Yes Key,windows,engine
1 1001 No Yes No windows
2 1002 No No No NaN
設定:
data = {'Car Id': [1000, 1001, 1002],
'Problem with Key?': ['Yes', 'No', 'No'],
'Problem with windows?': ['Yes', 'Yes', 'No'],
'Problem in the engine?': ['Yes', 'No', 'No']}
df = pd.DataFrame(data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/348726.html
