0

Given a Pandas data-frame(df) and a list(List1) containing lot of items which may or may not be data-frame column names. is it possible to print only those data-frame columns whose names are present in the given list.

Eg1: data-frame columns names are: 'one', 'two', 'three' List items are : 'one' , 'four', 'two'. Wanted to print only 'one' and 'two' data-frame column

List1=['one', 'four', 'two']
for item in List1:
    if item in df.columns:
        print(df.item)

Above code throws AttributeError: 'DataFrame' object has no attribute 'item' which is perfectly fine.

I am just trying to print only those data-frame columns whose names are present in the given list, if it is possible. Tried to find the workaround from pandas docs: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.columns.html

Vinay Sharma
  • 319
  • 1
  • 5
  • 13
  • 1
    `[col for col in df.columns if col in List1]`, or with sets: `list(set(df.columns) & set(List1))` – Erfan Feb 10 '20 at 10:19
  • @Erfan I am trying to print the data-frame COLUMN and not the common elements of df.columns and List1.. – Vinay Sharma Feb 10 '20 at 10:24
  • 1
    Then use `df[list(set(df.columns) & set(List1))]` or if you want to print one by: `for col in df.columns: if col in List1: print(df[col])`. – Erfan Feb 10 '20 at 10:26

0 Answers0