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.