Vivek Muraleedharan
Vivek Muraleedharan

Reputation: 1

How to cast only few columns in a pandas dataframe

I have a dataframe of 39 columns. I need to cast the type to int of the columns from 5(name=1980) to 39(2013). how do i do that?

d[1980:2013].astype(int) dataframe

Upvotes: 0

Views: 928

Answers (3)

Seawise
Seawise

Reputation: 11

df.loc[:,1980:2013].astype(int)

Upvotes: 1

RockAndRoleCoder
RockAndRoleCoder

Reputation: 320

You can solve this problem using a nested for-loop that starts with the index range.

for x in df.columns[5:40]:  <--pulls the columns you want to type cast
    for y in df[x]:  <-- pulls the array from said column
        y = int(y)   <--type casts the entire arrary

...repeats for each column inside your range. 

Upvotes: 0

Tojra
Tojra

Reputation: 683

Try this code:

for i in range(5,40):
    d.iloc[i,:]=map(int,d.iloc[i:])

Upvotes: 0

Related Questions