如何将 x 年和 y 个月的列转换为 [12(x)+y] 个月
How to convert a column of x years and y months into [12(x)+y] months
我的数据有一个 remaining_lease 列,它是 x 年 y 月
我想把它改成 [12(x)+y] 个月
我已经尝试了下面的代码,但错误不断出现
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)
首先 - 阅读 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
我的数据有一个 remaining_lease 列,它是 x 年 y 月
我想把它改成 [12(x)+y] 个月
我已经尝试了下面的代码,但错误不断出现
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)
首先 - 阅读 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