Home > Net >  Python Iteratively Read and Write Rows
Python Iteratively Read and Write Rows

Time:07-05

I am trying to read an excel file and write every fourth row into a new Excel file. I'm using Pandas to read and write, and "if int(num%4) == 0" to determine which rows to select, but the iteration and subsequent writing continue to escape me. I've tried my best to look up answers, but I'm a new programmer and struggling :/

CodePudding user response:

I did not understand what the problem is to be more specific, but you should try pandas' iloc property (or even loc depending on your df), check more info in here: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iloc.html

CodePudding user response:

If you're using Pandas I'm assuming you've load the data into a dataframe?

If so then consider this:

import pandas as pd
df = pd.read_csv('YourFile.csv')
df.iloc[::4]
#once you're done with the data you can save it to another csv file
df.to_csv('OutputFile.csv')

This will leave your dataframe df with the 4th, 8th, 12th, etc. rows from your original dataframe/file. You can then read/write to each row left in the dataframe df. To visualize the before and after just insert df.head() before and after the df.iloc[::4]

  • Related