如何将“ m年n个月”转换为“ m * 12 + n月”

问题描述 投票:-1回答:1

我有一个csv文件,其中有一列房子的“剩余租赁”,以m年零n个月表示,我想将其转换为月。

下面是它的外观。

https://i.stack.imgur.com/bh4Nc.png

在大熊猫中还是在Excel中有办法吗?

提前感谢

python-3.x pandas csv linear-regression
1个回答
0
投票

有pandas.Series对象的map函数。以下代码可以解决问题:

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

filepath = './example.csv' # write the filepath here as a string

house_lease = new pd.read_csv(filepath)
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.Series.map以一个参数作为参数的系列,字典或函数。

© www.soinside.com 2019 - 2024. All rights reserved.