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
270 views
in Technique[技术] by (71.8m points)

Python for loop save only last value to csv?

Used below lines of code for contour detection and its corresponding area calculation during printing the area all values are printed but while saving only last value got saved in CSV file

for cnt in contours:

    M= cv2.moments(cnt)
        #print(M)

    if M["m00"] != 0:

        cx = int(M["m10"] / M["m00"])
        cy = int(M["m01"] / M["m00"])
    else:
        cx, cy = 0,0

    center = (cx,cy)


    area = cv2.contourArea(cnt)
    #V1 = np.asarray(area)
    print(area)

    df = pd.DataFrame()
    df['Area'] = area

    df.to_csv("C:pfmdataframe_csvL501.csv")
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In every iteration of the loop, you create a new, empty DataFrame, put one thing into it, and write it out to a file. Each time, it writes over the previous output and what is left at the end is the last one. This happens because the file is opened in write mode by default.

(If "write mode" means nothing to you, you should review Python file open modes in your favorite language reference.)

Fortunately, the to_csv function has a mode parameter that you can set to 'a' to open the file for appending. If you do that, each write should append to the end of the file.

Alternately, you could accumulate all the output in one big DataFrame and write the whole thing out once after the loop terminates. This would probably be faster, but would require more memory.


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

...