[英]How to individually update columns in a csv file using Python
每當我的代碼運行時,我都試圖在 csv 文件中插入(更新)值。
這是我的 csv 文件內容:
col1 | col2 | col3
value1,value2,value3
當我運行我的代碼時,我只想更新 col2 等於“value1”的行。 因此,col2 和 col3 值將是我嘗試更新的唯一值。 例如,在我運行我的腳本后它看起來像這樣:
col1 | col2 | col3
value1,new_value2,new_value3
這是我的代碼:
但是,當我運行這段代碼時,它給了我一個錯誤。 關於如何修復此代碼以運行的任何想法或建議?
最好的選擇是使用pd.where
有選擇地替換每列的值
df['col2'] = df['col2'].where(df['col1'] != 'value1', other='new_value2')
df['col3'] = df['col3'].where(df['col1'] != 'value1', other='new_value3')
這會產生:
col1 col2 col3
0 value1 new_value2 new_value3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.