我有一个csv文件,其中有一列房子的“剩余租赁”,以m年零n个月表示,我想将其转换为月。
下面是它的外观。
https://i.stack.imgur.com/bh4Nc.png
在大熊猫中还是在Excel中有办法吗?
提前感谢
有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以一个参数作为参数的系列,字典或函数。