dataframe填充到指定的行数

辅助函数写法如下:

def reach_target_line(dataframe: pd.DataFrame, target_line, fill_mark=0):
    if dataframe.shape[0] >= target_line:
        return dataframe[:target_line]
    else:
        fill_df = pd.DataFrame(np.zeros(shape=(target_line - dataframe.shape[0], dataframe.shape[1])),
                               columns=dataframe.columns)
        fill_df.loc[:, :] = fill_mark
        return dataframe.append(fill_df)

案例代码

import pandas as pd
import numpy as np


def reach_target_line(dataframe: pd.DataFrame, target_line, fill_mark=0):
    if dataframe.shape[0] >= target_line:
        return dataframe[:target_line]
    else:
        fill_df = pd.DataFrame(np.zeros(shape=(target_line - dataframe.shape[0], dataframe.shape[1])),
                               columns=dataframe.columns)
        fill_df.loc[:, :] = fill_mark
        return dataframe.append(fill_df)


if __name__ == '__main__':
    df = pd.DataFrame(data=np.random.randint(0, 10, size=(10, 2)), columns=['a', 'b'])
    new_df = reach_target_line(df, 15)
    print(df.shape)
    print(new_df.shape)

你可能感兴趣的:(python,数据处理,python)