简体   繁体   中英

Writing long list using pandas to save in csv files

I am using the following to write to a csv file with python:

submission = pandas.DataFrame({
    "label": data["label"],
    predictors[0]: data[predictors[0]]
})

and later I write a csv file with:

submission.to_csv("test.csv", index=False)

Now, my predictor list is a long list of 1000+ elements, and obviously I cannot write all those lines by hand

submission = pandas.DataFrame({
    "label": data["label"],
    predictors[0]: data[predictors[0]]
    predictors[1]: data[predictors[1]]
    predictors[2]: data[predictors[2]]
    predictors[3]: data[predictors[3]]

    ...
    })

I tried

submission = pandas.DataFrame({
    "label": data["label"],
    for i in range(lengthofpredictors):
       predictors[i]: data[predictors[i]]
})

but it does not work, as

submission = pandas.DataFrame({
    "label": data["label"],
    predictors: data[predictors]
})

won't work. How do I do it?

How about using list comprehension to create the dictionary?

tmp = dict([("label", data["label"])] + \
    [(predictors[i], data[predictors[i]]) for i in range(784)])

Then

 submission = pandas.DataFrame(tmp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM