Dan Jel Schneider
Dan Jel Schneider

Reputation: 49

Slicing Pandas data frame into two parts

Actually I thougth this should be very easy. I have a pandas data frame with lets say 100 colums and I want a subset containing colums 0:30 and 77:99.

What I've done so far is:

df_1 = df.iloc[:,0:30]

df_2 = df.iloc[:,77:99]

df2 = pd.concat([df_1 , df_2], axis=1, join_axes=[df_1 .index])

Is there an easier way?

Upvotes: 1

Views: 545

Answers (1)

jezrael
jezrael

Reputation: 862431

Use numpy.r_ for concanecate indices:

df2 = df.iloc[:, np.r_[0:30, 77:99]]

Sample:

df = pd.DataFrame(np.random.randint(10, size=(5,15)))
print (df)
   0   1   2   3   4   5   6   7   8   9   10  11  12  13  14
0   6   2   9   5   4   6   9   9   7   9   6   6   1   0   6
1   5   6   7   0   7   8   7   9   4   8   1   2   0   8   5
2   5   6   1   6   7   6   1   5   5   4   6   3   2   3   0
3   4   3   1   3   3   8   3   6   7   1   8   6   2   1   8
4   3   8   2   3   7   3   6   4   4   6   2   6   9   4   9

df2 = df.iloc[:, np.r_[0:3, 7:9]]
print (df2)
   0  1  2  7  8
0  6  2  9  9  7
1  5  6  7  9  4
2  5  6  1  5  5
3  4  3  1  6  7
4  3  8  2  4  4

df_1 = df.iloc[:,0:3]
df_2 = df.iloc[:,7:9]
df2 = pd.concat([df_1 , df_2], axis=1, join_axes=[df_1 .index])
print (df2)
   0  1  2  7  8
0  6  2  9  9  7
1  5  6  7  9  4
2  5  6  1  5  5
3  4  3  1  6  7
4  3  8  2  4  4

Upvotes: 1

Related Questions