joycey joycey - 7 months ago 13
Python Question

Python function definition on two list

Year Month Year_month
2009 2 2009/2
2009 3 2009/3
2007 4 2007/3
2006 10 2006/10

Year_month
200902
200903
200704
200610


I would like to combine the year and month columns into the format as Year_month (i.e. replace the original one). How could I do it? The following approach seems not working in Python. Thanks.

def f(x, y)
return x*100+y

for i in range(0,filename.shape[0]):
filename['Year_month'][i] = f(filename['year'][i] ,filename['month'][i])

Answer

I think you can use zfill:

df['Year_month'] = df.Year.astype(str)  + df.Month.astype(str).str.zfill(2)
print df
   Year  Month Year_month
0  2009      2     200902
1  2009      3     200903
2  2007      4     200704
3  2006     10     200610