Programmatically convert pandas dataframe to markdown table

后端 未结 13 1300
梦毁少年i
梦毁少年i 2020-12-13 03:44

I have a Pandas Dataframe generated from a database, which has data with mixed encodings. For example:

+----+-------------------------+----------+-----------         


        
13条回答
  •  猫巷女王i
    2020-12-13 04:31

    I have tried several of the above solutions in this post and found this worked most consistently.

    To convert a pandas data frame to a markdown table I suggest using pytablewriter. Using the data provided in this post:

    import pandas as pd
    import pytablewriter
    from StringIO import StringIO
    
    c = StringIO("""ID, path,language, date,longest_sentence, shortest_sentence, number_words , readability_consensus 
    0, data/Eng/Sagitarius.txt , Eng, 2015-09-17 , With administrative experience in the prepa... , I am able to relocate internationally on short not..., 306, 11th and 12th grade
    31 , data/Nor/Høylandet.txt  , Nor, 2015-07-22 , Høgskolen i Østfold er et eksempel..., Som skuespiller har jeg både..., 253, 15th and 16th grade
    """)
    df = pd.read_csv(c,sep=',',index_col=['ID'])
    
    writer = pytablewriter.MarkdownTableWriter()
    writer.table_name = "example_table"
    writer.header_list = list(df.columns.values)
    writer.value_matrix = df.values.tolist()
    writer.write_table()
    

    This results in:

    # example_table
    ID |           path           |language|    date    |                longest_sentence                |                   shortest_sentence                  | number_words | readability_consensus 
    --:|--------------------------|--------|------------|------------------------------------------------|------------------------------------------------------|-------------:|-----------------------
      0| data/Eng/Sagitarius.txt  | Eng    | 2015-09-17 | With administrative experience in the prepa... | I am able to relocate internationally on short not...|           306| 11th and 12th grade   
     31| data/Nor/Høylandet.txt  | Nor    | 2015-07-22 | Høgskolen i Østfold er et eksempel...        | Som skuespiller har jeg både...                      |           253| 15th and 16th grade   
    

    Here is a markdown rendered screenshot.

提交回复
热议问题