0

I have dataframe like below

df.head(2)
A B C D E F
1 1 1 3 4 5
3 4 5 2 3 1

I want to dynamically select columns based input passed .

Input

Enter number of columns?
 3

Enter  column names?
   A,E,C

Expected Output

 A  E  C
 1  4  1
 3  3  5

How can this be done in Python?

3
  • for integer based slicing use iloc : df.iloc[:,:3] for column labels use loc : df.loc[:,['A','E','C']] Commented Jan 27, 2020 at 4:18
  • @anky_91, I want pass the column selections as inputs to the user. Commented Jan 27, 2020 at 4:22
  • In that case you can split the input on comma and create a list. s="A,B,C" , then split like: s.split(',') and pass it under .loc[] as shown above. BDW you should be able to handle cases where user inputs a column which is not there in the dataframe, in such cases use df.reindex(columns=list_of_cols_after_split) Commented Jan 27, 2020 at 4:25

3 Answers 3

3

You could just ask for the column names.

cols = input("Column names?")
df = df[cols]

Note: columns will need to be entered as a list e.g. ['A', 'B', 'C'].

Sign up to request clarification or add additional context in comments.

Comments

0

Adding a slightly cleaner solution to Dance Party's (just so you don't need to input a list) you could do -

cols = input("Column names?")
cols = cols.split(', ')
df = df[cols]

This way your input can just be A,E,C and does not need to be a list

Comments

0
   A  B  C  D  E  F
0  1  1  1  3  4  5
1  3  4  5  2  3  1

select = str(input("insert required cols to display (coma seperated)"))
dfx[select.split(',')]

1 Comment

While this code may provide a solution to the OP's question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.