Home > other >  Select title of column with Pandas?
Select title of column with Pandas?

Time:10-03

Lets say I have a dataframe:

      Title1     Title2
0       420        50
1       380        40
2       390        45

How can I get as output only the name of the title of the first column (Title1) without the values of the column? I've tried iloc but that doesn't work of course.

CodePudding user response:

If dfis your dataframe, then the following should work:

first_col = df.columns[0]

See here for more info.

CodePudding user response:

lst = list(df.columms)
lst[0]

It will give you the all the column name in a list... & first item fetched using indexing...

CodePudding user response:

Are you looking for:

data={"Title1":[10,20,30],"Title2":[100,50,30]}
df=pd.DataFrame(data)

print(df)
for col in df.columns:
    print(col)
    print("---------")
    print("print of column:")
    print(df[col])

Result: Intial df:

   Title1  Title2
0      10     100
1      20      50
2      30      30

first column name:

Title1

print of first column:

0    10
1    20
2    30
Name: Title1, dtype: int64

Second column name:

Title2

print of second column:

0    100
1     50
2     30
Name: Title2, dtype: int64
  • Related