0

code:

i = 0
while i<3:
    def avoid_repeat_df():
        rows = []
        for i in range(1):
            try:
                rows. append([i, i + 2])
                df = pd. DataFrame(rows, columns=["Aaa", "Bee"])
                df.to_csv('example.csv')#mode='a' write the ouput same as df else only last occurance
                print(df)  
            except:
                pass  
    avoid_repeat_df()        
    i+=1    

it prints output as

 Aaa  Bee
0    0    2
   Aaa  Bee
0    0    2
   Aaa  Bee
0    0    2

But in csv only last line writes (in append mode same as df output all the line)

What i expect : avoid repeating column header

 Aaa  Bee
0    0    2
0    0    2  
0    0    2

Hope i explained in details. Thanks for your time and help.

1
  • What is your overall goal? Why would you not create your dataframe first and then export it to csv? This seems overly complex. Commented Jul 13, 2021 at 8:30

3 Answers 3

1

Try defining rows variable(list) outside of the while loop:

i = 0
rows = []
while i<3:
    def avoid_repeat_df():
        for i in range(1):
            try:
                rows. append([i, i + 2])
                df = pd. DataFrame(rows, columns=["Aaa", "Bee"])
                df.to_csv('example.csv')#mode='a' write the ouput same as df else only last occurance
                print(df)  
            except:
                pass  
    avoid_repeat_df()        
    i+=1 

Now If you check example.csv:

,Aaa,Bee
0,0,2
1,0,2
2,0,2
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Works fine but when printing df it prints cumulative rows like starts from 1 and keeps on adding lines each iterate. But csv fine. That's solved my issue. Thanks
1

try this:

i = 0
rows = []
while i<3:
    l = [[k, k + 2] for k in range(1)]
    rows.extend(l)
    i+=1
df = pd.DataFrame(rows,columns=["Aaa", "Bee"])
df.to_csv("example.csv")
print(df)

Output

   Aaa  Bee
0    0    2
1    0    2
2    0    2

1 Comment

Thanks, I have to use for loop with try and exception. Your answer missed that try and exception loop and df only for try output. Anyhow Thanks for immediate Response.
0

I see 2 ways to handle this, one as mentioned by @Anurag Dabas, to move data frame definition outside the loop. I can help you with the second one where while writing you can simply use header option in to_csv method.

While using mode='a', use header=False, this will skip writing column header each time.

But according to what is presented, the best way would be to use list instead of creating a dataframe, as it is computationally inefficient.

i = 0
rows = list()
while i<3:
    def avoid_repeat_df():
        global rows
        for i in range(1):
            try:
                rows.append([i, i + 2])
            except:
                pass  
    avoid_repeat_df()        
    i+=1
df = pd. DataFrame(rows, columns=["Aaa", "Bee"])
df.to_csv('example.csv')
print(df)  

If you still want to create df only

i = 0
while i<3:
    def avoid_repeat_df():
        rows = list()
        for i in range(1):
            try:
                rows.append([i, i + 2])
                df = pd.DataFrame(rows, columns=["Aaa", "Bee"])
                if os.path("example.csv").exists():
                   df.to_csv("example.csv", mode="a", header=False)
                else:
                   df.to_csv("example.csv")
                # This won't change actual df though
                print(df)
            except:
                pass  
    avoid_repeat_df()        
    i+=1  

You could also append to df and save when all your iterations have been completed but that would be as good as creating a list and then creating data frame out of it.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.