0

Real simple question that I cant seem to get. For the following single column DF:

Cost  
1

What syntax would I use to print "Cost = 1". i know print df['Cost'] would be 1. But i want the column name to be in the output.

2
  • 1
    What do you want if the column has more than one row? Commented May 2, 2018 at 16:53
  • well if it has more than one thats fine. i just want to be able to call whatever column's header when i call the value Commented May 2, 2018 at 16:59

2 Answers 2

2

This is one way without having to reference your column name(s) explicitly.

df = pd.DataFrame({'Cost': [1]})

for k in df:
    print('{0} = {1}'.format(k, df[k].iloc[0]))

# Cost = 1
Sign up to request clarification or add additional context in comments.

Comments

0

If you have more than one column

df = pd.DataFrame({'Product':['x','y'],'Cost': [1,2]})
col_names=df.columns
for row in range(0,len(df)):
    for col_name,col in zip(col_names,df.iloc[row]):
        print("{}={}".format(col_name,col))

Comments

Your Answer

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