Python根据每列的值将两列合并为一

时间:2018-10-31 10:32:46

标签: python data-structures

我正在this数据集中工作,我想基于此将yr_built和yr_renovated合并为一个,最好合并为yr_built:如果yr_renovated中的值大于0,那么我希望拥有这个值,否则为yr_built的值。

您能帮我吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您在这里。基本上,数据框需要熊猫,然后使用numpy创建新列以检查'yr_renovated'的值是否大于零,否则使用'yr_built'

import pandas as pd
import numpy as np
df = pd.read_csv('https://raw.githubusercontent.com/Jonasyao/Machine-Learning-Specialization-University-of-Washington-/master/Regression/Assignment_four/kc_house_data.csv', error_bad_lines=False)
df=df[['yr_built','yr_renovated','date','bedrooms']]
newdata['MyYear']=np.where(df['yr_renovated'] > 0,df['yr_renovated'],df['yr_built'])
newdata

enter image description here

相关问题