[Python] Writing pandas df.max().to_csv()

Discussão em 'Python' iniciado por Stack, Maio 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have pandas dataframes with up to 50 plus columns. This is cumulative rainfall data for different years at different stations. For a given dataframe (i.e. a station), i would like to print the year and the maximum value for that year. When I run my code below, it prints, both in the csv file and on the screen, each year and the corresponding value on one line, as

    Date 183.0
    Mean 975.1
    1978 1125.5
    1979 1134.7
    1980 983.9
    1981 1041.7
    .... .....


    The second time i run the code it produces, both in the csv file and on the screen,

    "Date Mean 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024" "183 975.1 1125.5 1134.7 983.9 1041.7 936.1 1115.6 938.9 1061.8 1046.4 827.8 841.4 963.9 867.0 902.1 1053.2 734.9 1110.0 998.6 559.3 1338.5 821.7 820.3 1198.9 881.8 967.7 675.8 1049.7 743.7 1065.3 0.0 850.8 745.3 746.5 643.0 1117.8 0.0 651.5 0.0 0.0 1189.7 976.3 1312.3 940.6 997.9 853.2 969.1 0.0"


    Is there anything I can change in the code to have always as in the first format?

    import pandas as pd
    df = pd.read_csv('/home/zmumba/CLIMAT_PROGRAMS/Output/RAINFALL/Cumul/ISOKA001.txt')
    zero_cols = [ col for col, is_zero in ((df == 0).sum() == df.shape[0]).items() if is_zero ]

    df.drop(zero_cols, axis=1, inplace=True)
    df.max().to_csv('ISOKA001.txt', header=None, index=True, sep=' ')

    with open('ISOKA001.txt') as f:
    for line in f:
    line = line.rstrip('\r\n')
    print(line)


    Please help.

    Continue reading...

Compartilhe esta Página