kantditlaverite
kantditlaverite

Reputation: 27

How to Select Rows and Columns of Dataframe?

I have a dataframe with 4 columns and 6 rows, I want to select 2nd and 4th columns and 1st and 6th rows of this dataframe and create a new dataframe. How can i do this?

Upvotes: 1

Views: 446

Answers (1)

Ammar Sabir Cheema
Ammar Sabir Cheema

Reputation: 990

You can use the code given below, to do this but you have to be careful with the fact that in pandas the indexing starts from 0 which is the first column or could be first row when you are retrieving it.

>>> import pandas as pd
>>> 
>>> dictA = {'col1': ['tom', 10,20,56,2,3,4],'col2': ['tom', 10,20,56,2,3,4],'col3': ['tom', 10,20,56,2,3,4],'col4': ['tom', 10,20,56,2,3,4]}
>>>         
... dfA = pd.DataFrame(dictA)
>>> dfA
  col1 col2 col3 col4
0  tom  tom  tom  tom
1   10   10   10   10
2   20   20   20   20
3   56   56   56   56
4    2    2    2    2
5    3    3    3    3
6    4    4    4    4
>>> new_df = dfA.iloc[[0,5],[2,3]]
>>> new_df
  col3 col4
0  tom  tom
5    3    3

For more details have a look here

Upvotes: 1

Related Questions