0 votes
1 view
in Machine Learning by (14.6k points)

I have data in different columns but I don't know how to extract it to save it in another variable.

index a b c

1 2 3 4

2 3 4 5

How do I select 'a', 'b' and save it into df1?

I tried

df1 = df['a':'b']

df1 = df.ix[:, 'a':'b']

None seem to work.

1 Answer

0 votes
by (33.2k points)

In pandas, you can select multiple columns by their name, but the column name gets stored as a list of the list that means a dictionary. It means you should use [ [ ] ] to pass the selected name of columns. This method df[['a','b']] produces a copy.

For example:

df1 = df[['a','b']]

You can also use ‘.iloc’ method to access the list by column name. It is efficient to access the column by the index number of a column name.

For example:

df1 = df.iloc[:,0:2]

Hope this answer helps.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !