0

I'm trying to add new rows with value '0' in my txt file to make total no of rows divisible by 3, here is the code:

import pandas as pd

# read text file into pandas DataFrame
def process():
    df = pd.read_csv("./calibration.txt", sep=' ', header=None)
    if len(df)%3!=0:
        print("add zero in the last")
        number = 0
        with open('./calibration.txt', 'a') as f:
            f.write('\n%d' % number )
            f.close()
    #else:
     #   print("dont add zero")
if __name__=='__main__':
    process()
    df = pd.read_csv("./calibration.txt", sep=" ", header=None)
    df_new = pd.DataFrame(df.iloc[: , 0].values.reshape((-1, 3)))
    pd.set_option("display.max_rows", None, "display.max_columns", None)
    df_new.to_csv( index=False)
    print(df_new)

Now the problem is its writing only one new row with value '0' but I need to keep writing new rows with value '0' until total no. of rows get divisible by 3. Any help will be highly appreciable as I'm new to play with rows and columns. TIA

  • What is the shape of your dataframe, and what are its headers? – Joshua Voskamp Nov 15 '22 at 23:59
  • 1
    Think of it this way: the maximum number of "0" rows you need to add is 2. Just repeat the process. Then think about how to implement `process()` so that you don't write the file twice in the case that two new rows are required. – Michael Ruth Nov 16 '22 at 00:27

1 Answers1

0

Try something like

import numpy as np
import pandas as pd

# extracted as config var; allows for changing dataframe width in one location
WIDTH = 3

def process(path):
    df = pd.read_csv(path, sep=' ', header=None)
    vals = df.iloc[:,0].values
    remainder = len(vals) % WIDTH
    
    # pad with nothing on the left, WIDTH - remainder `0`s on the right
    padded = np.pad(vals, (0, WIDTH - remainder))
    return pd.DataFrame(padded.reshape((-1, WIDTH)))

if __name__=="__main__":
    df = process("./calibration.txt")
    pd.set_option("display.max_rows", None, "display.max_columns", None)
    print(df)
    df.to_csv(index=False)
Joshua Voskamp
  • 1,855
  • 1
  • 10
  • 13