'Using pyMannKendall python package for testing the trend for gridded rainfall data

I am using pyMannKendall python package for testing the trend for gridded rainfall data. I am successful in carrying out trend analysis for all the grids but now I want to write the results of all the grids to a CSV file. I am new to coding and is facing a problem. Attached below is my code.

import pymannkendall as mk
import csv
import numpy as np

df = pd.read_csv("pr_1979_2018.csv", index_col = "Year")

for i in df.columns:

    res = mk.hamed_rao_modification_test(df[i])

    new_df=pd.DataFrame(data=a, index= ['trend','h','p','z', 'Tau', 
    's','var_s','slope', 'intercept'], columns=['stats'], dtype=None)

new_df.to_csv("Mk_2.csv")

On running this code I am getting only a single column in my CSV file, however I want results of all the columns in my resulting CSV file. Please help



Solution 1:[1]

You can convert your rows into columns in Python using Transpose() in Pandas before export.

Try this:

new_df = pd.DataFrame.transpose(new_df)

new_df.to_csv("Mk_2.csv",header=True)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1