Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

pandas - Why am I getting column headers for each index of a dataframe in Python?

Hi so currently I am trying to create an empty dataframe in python using this code:

for i in range (len('bus0')):
    empty_df = pd.DataFrame(np.nan, index=[i], columns=['bus0', 'bus1'])
    print(empty_df)

But I am getting an output (below) which reprints the column headers bus0 and bus1 for each index in the dataframe:

 bus0  bus1
0   NaN   NaN
   bus0  bus1
1   NaN   NaN
   bus0  bus1
2   NaN   NaN
   bus0  bus1
3   NaN   NaN

I do not want the column headers to keep reappearing for each index, I just want them to show up once at the top. How does one achieve this?

question from:https://stackoverflow.com/questions/65831090/why-am-i-getting-column-headers-for-each-index-of-a-dataframe-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a few things going on. You're both reassigning and reprinting the dataframe every time you go through the for loop.

To see what I mean, the following code (just taking the print statement out of the for loop) only prints the last data assigned to the dataframe.

for i in range (len('bus0')):
    empty_df = pd.DataFrame(np.nan, index=[i], columns=['bus0', 'bus1'])

# print(empty_df)
'''
bus0  bus1
3   NaN   NaN
'''

Instead of reassigning the whole dataframe, I would declare it before the for loop and just add each row in the for loop using .iloc. You can also use .iloc to assign different values to different rows while iterating through the for loop.

import pandas as pd
import numpy as np

empty_df = pd.DataFrame(columns=['bus0', 'bus1'])

for i in range (len('bus0')):
    empty_df.loc[i] = np.nan

# print(empty_df)
'''
bus0 bus1
0  NaN  NaN
1  NaN  NaN
2  NaN  NaN
3  NaN  NaN
'''

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...