首頁  >  文章  >  後端開發  >  如何在整列中用減號替換底線?

如何在整列中用減號替換底線?

王林
王林轉載
2024-02-12 17:03:04379瀏覽

如何在整列中用減號替換底線?

問題內容

下圖是我的列表,我想在其中編輯兩個列以供將來在資料清理過程中進行分析:

執行程式碼 bike_share_data["start_lng"].dtypes 時,「start_lng」和「end_lng」欄位的內容為 dtype('o')

#現在我想用減號(-)替換下劃線(_)並使整個列的資料類型為浮點數。

我已經單獨測試了程式碼,如下所示:

import pandas as pd
d =[ '_1.0', '_2.0', '_3.0']

d=[s.replace('_','-') for s in d]
print(d)

結果是['-1.0', '-2.0', '-3.0']。

但無法在 bike_share_data["start_lng"] 欄位上實作它。我該怎麼做?


正確答案


您可以使用str.replace() 方法執行替換,然後使用astype() 更改資料類型。

# sample DataFrame with a "start_lng" column containing strings
data = {'start_lng': ['_1.0', '_2.0', '_3.0']}
Bike_share_data = pd.DataFrame(data)

# Replace underscores with minus signs & convert the column to float
Bike_share_data["start_lng"] = Bike_share_data["start_lng"].str.replace('_', '-').astype(float)

以上是如何在整列中用減號替換底線?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除