iterating over long list to generate smaller lists and append to csv

iterating over long list to generate smaller lists and append to csv



Struggling with doing this and was wondering if someone can help.
I have a code that generates a large list of 300 items.
I want to write this to a csv file using pandas but write different sub lists to different rows.
for example
Take items 0-7 and write to one row, then 1-8, 2-9 and so on until 293-300.
currently what i have being doing is this and manually changing the selection in
df.iloc[:,2:9]
but i was hoping there would be a way to automate this with a loop.


df.iloc[:,2:9]



This is what i have as an example so far.
sncomo is just a package to generate data. its output is what I want to split up and save to a csv file.


import sncosmo
import pandas as pd

days_apart = list(range(55, 300))
model = sncosmo.Model(source="hsiao")
model.set(z=1.5, t0=100)
y = model.bandmag('desr', 'ab', days_apart)
df = pd.DataFrame([y])
df1 = df.iloc[:,2:9]
with open("test_data.csv", "a") as f:
df1.to_csv(f, header=False)



Hope someone can help thanks!




1 Answer
1



I would just use a for loop with enumerate


for


enumerate


import sncosmo
import pandas as pd

days_apart = list(range(55, 300))
model = sncosmo.Model(source="hsiao")
model.set(z=1.5, t0=100)
y = model.bandmag('desr', 'ab', days_apart)
df = pd.DataFrame([y])
for i, j in enumerate(range(6,300)):
df1 = df.iloc[:,i:j+1]
with open("test_data.csv", "a") as f:
df1.to_csv(f, header=False)



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Some of your past answers have not been well-received, and you're in danger of being blocked from answering.



Please pay close attention to the following guidance:



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)