Home > Net >  How get first line from Pandas and iterate columns values?
How get first line from Pandas and iterate columns values?

Time:05-27

I have a dataframe without headers. I want to read first line from dataframe then iterate all columns values to show user and suggest to set column name by value:

How to do that?

A B C 
1 2 3
4 5 6
7 8 9

User must see:

1 ask to enter column name
2 ask to enter column name
3 ask to enter column name

Done.

I tried this:

for colindex in range(len(df.columns)):
    colvalue = df[colindex].values[0]

CodePudding user response:

If you want user input - then you need the input function -

user_col_names = []
for val in df.loc[0]:
    col_name = input(f'{val}\tEnter column name: ')
    user_col_names.append(col_name)

Output

1       Enter column name: a
2       Enter column name: b
3       Enter column name: c

# user_col_names                                                                                                                  
# ['a', 'b', 'c']

Do note that ensuring these column names are valid is still up to you.

CodePudding user response:

import pandas as pd

Create a dataframe without columns

df = pd.DataFrame([*zip([1,2,3],[4,5,6],[1,2,3])])

iterate every column of the dataframe and save the first value of each column , ask for the input and rename dataframe column , finally print the dataframe to see the result

for column in df.columns[0:]:

   column_first_value=str(df[column][0])
   column_name = input(f'{column_first_value}\t Set column name: ')
   df = df.rename(columns = {column:column_name})




print(df.to_string(index=False))

Output

enter image description here

  • Related