作業流程 =>
- 讀取 CSV 檔案并獲取單價列資料
- 轉換列資料價格并創建一個名為“Fabric”的新列
- 將輸出保存為 xlsx
樣本:
Unit Price
----------
330
350
380
I want to convert this data
Fabric
------
Card
Combed
Viscos
我的代碼:
##Fabric Data
getFabric = df_new['Unit Price']
result = []
for fabric in getFabric:
if fabric == 310:
result.append("Card")
elif fabric == 330:
result.append("Combed Dawah")
elif fabric == 350:
result.append("Combed Regular")
elif fabric == 490:
result.append("Viscos")
elif fabric == 550:
result.append("Pleated")
else:
result.append(fabric)
df_new['Fabric'] = result
錯誤 :
uj5u.com熱心網友回復:
這很容易,伙計...
your_df["Fabric"] = your_df["Unit Price"].apply(lambda x: str(x).replace("330", "Card"))
# do this for every conversion
your_df.to_csv("filename.csv")
上述代碼可以保存為 CSV 檔案,可以在 MS EXCEL 中查看
uj5u.com熱心網友回復:
Insted 迭代列值。試試這個,
呼叫的pandas 內置函式.replace()可用于在不迭代的情況下替換列中的值
df_new['Unit Price'].replace({310: 'Card', 330: 'Combed Dawah', 350: 'Combed Regular', 490: 'Viscos', 550: 'Pleated'}, inplace=True)
上面的代碼將成功地替換資料框列值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/479705.html
上一篇:PandasDataFrame-根據鍵洗掉/替換字典值
下一篇:如何從熊貓資料框中獲取不同的行?
