Python 如何转换;“m年n个月”;变成;m*12+;n个月“;

Python 如何转换;“m年n个月”;变成;m*12+;n个月“;,python,pandas,Python,Pandas,我有一个csv文件,其中有一列房子的“剩余租约”,以m年和n个月表示,我想将其转换为月份 下面是它的样子 有没有办法在pandas或excel中执行此操作?有pandas.Series对象的映射功能。以下代码可以实现此目的: import pandas as pd def lease_string_to_months(time): split_string = time.split(' ') months = 12*int(split_string[0]) + int(spl

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

下面是它的样子


有没有办法在pandas或excel中执行此操作?

有pandas.Series对象的映射功能。以下代码可以实现此目的:

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将一个系列、一个字典或一个函数的一个参数作为参数。

欢迎使用SO,请仅以文本形式发布输入和预期输出的示例,而不以任何其他形式发布。另外,将您的示例包装在代码标签中,然后让我们知道