我的資料有一個剩余租約列,它在 x 年和 y 個月內我想將其更改為 [12(x) y] 個月
![如何將 x 年和 y 個月的列轉換為 [12(x) y] 個月](https://img.uj5u.com/2022/03/24/95a7cacac10441f8a522c2fbd6a39e2f.png)
我已經嘗試了下面的代碼,但一直出現錯誤
import pandas as pd
def lease_string_to_months(time):
split_string = time.split(' ')
months = 12*int(split_string[0]) int(split_string[2])
return months
df1 = 'resale-flat-prices-based-on-registration-date-from-jan-2017-onwards.csv' # write the filepath here as a string
house_lease = pd.read_csv(df1)
new_header = house_lease.iloc[0]
house_lease = house_lease[1:]
house_lease.columns = new_header
house_lease['remaining_lease'].map(lease_string_to_months)
uj5u.com熱心網友回復:
首先 - 閱讀pd.read_csv()并檢查您所擁有的內容house_lease。換句話說,我懷疑您是否需要大部分轉換。
由于我沒有您的 cvs 檔案,因此我在這里制作了玩具示例,拆分remaining_lease(字串)列,將第 [0] 列和第 2 列轉換為數字,將 12*Y M 推送到資料框中的新months列。
import pandas as pd
d = {'remaining_lease': ['55 years 12 months', '12 years 01 months']}
df = pd.DataFrame(d)
rdf = df['remaining_lease'] \
.str.split(r" ", expand=True) \
.iloc[:, [0,2]] \
.apply(pd.to_numeric)
df['months'] = 12*rdf[0] rdf[2]
print(df)
> remaining_lease months
0 55 years 12 months 672
1 12 years 01 months 145
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/448451.html
