1

I have to iterate through column=0 and if I find any integer like 2010,2018,2017 etc in my column =0, I have to assign that to all the values in column=0 as year.

PS:-column=0 is an object datatype.

My DF: 0 1
Nan Banks National Banks Axis Bank Nan ICICI Nan PNB 2010 KYB Nan Indus Ind Nan Karur

My desired output: 0 1
2010 Banks 2010 Axis Bank 2010 ICICI 2010 PNB 2010 KYB 2010 Indus Ind 2010 Karur

E_net4
  • 27,810
  • 13
  • 101
  • 139
  • Welcome to StackOverflow. Please take the time to read this post on [how to provide a great pandas example](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](https://stackoverflow.com/help/minimal-reproducible-example) and revise your question accordingly :) – Andrea Jan 03 '20 at 08:48
  • What is expected output if `Nan` after `National Banks` is `2015` ? – jezrael Jan 03 '20 at 10:02
  • Firstly, thank you jezrael for your time...i just want to replace all(including nan,national banks) the values in column=0 with the integer value i get (ex.2010). – Harsha Ragyari Jan 03 '20 at 10:10

1 Answers1

1

Convert column to numeric by to_numeric and then convert all numbers outside range to missing values to NaNs by Series.where with mask by Series.isin:

s = pd.to_numeric(df[0], errors='coerce')
df[0] = s.where(s.isin(range(2010, 2020)))
print (df)
        0          1
0     NaN      Banks
1     NaN  Axis Bank
2     NaN      ICICI
3     NaN        PNB
4  2010.0        KYB
5     NaN  Indus Ind
6     NaN      Karur
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • The above answer is partially useful....i want to replace the column=0 values with whatever integer value i get(ex.2010,2011etc)...should we use iteritems()? – Harsha Ragyari Jan 03 '20 at 10:12
  • @HarshaRagyari - in column is always only one unique year? If yes, then use `df[0] = s.where(s.isin(range(2010, 2020))).dropna().iat[0]` – jezrael Jan 03 '20 at 10:14
  • @HarshaRagyari - If possible multiple values then `df[0] = s.where(s.isin(range(2010, 2020))).ffill().bfill()` should help. – jezrael Jan 03 '20 at 10:16
  • 1
    Ty, i am able to get my desired output now.. t=pd.to_numeric(df[0],errors='coerce') t df[0]=t.where(t.isin(range(2005,2020))).dropna().values[0] df[0] – Harsha Ragyari Jan 03 '20 at 10:32