pandas 在txt文件中添加值为'0'的行,使总行数可被3整除

w3nuxt5m  于 2022-11-20  发布在  其他
关注(0)|答案(1)|浏览(144)

我试图在我的txt文件中添加值为'0'的新行,使行数可被3整除,代码如下:

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)

现在的问题是它只写一个新的行与值'0',但我需要继续写新的行与值'0',直到总数的行数得到整除3.任何帮助将是非常值得赞赏的,因为我是新的发挥行和列. TIA

qhhrdooz

qhhrdooz1#

尝试以下内容

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)

相关问题