如何将 x 年 y 月的列转换为 [12(x)+y] 个月

发布于 2025-01-16 21:41:46 字数 695 浏览 0 评论 0原文

我的数据有一个剩余租赁列,该列位于 x 年 y 个月内 我想将其更改为 [12(x)+y] 个月 Here is a picture of the data

我已尝试下面的代码,但不断发生错误

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)

My data has a remaining_lease column where it is in x years and y months
I would like to change it into [12(x)+y] months
Here is a picture of the data

I have tried the code below but an error keeps occuring

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

許願樹丅啲祈禱 2025-01-23 21:41:46

首先 - 阅读 pd.read_csv() 以及检查 house_lease 中的内容。换句话说,我怀疑你是否需要大部分转变。

由于我没有您的 cvs 文件,因此我在这里制作了一个玩具示例,拆分 remaining_lease (字符串)列,转换为第 [0] 列和第 [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

First - read about pd.read_csv() as well as inspect what you have in house_lease. In other words, I doubt that you need most of your transformations.

Since I don't have your cvs file, I made toy example here, split remaining_lease (string) column, converted [0]th & 2th columns to number, pushed 12*Y+M to a new months column in dataframe.

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文