你可以将一个数据框转换成一个垂直排列的Markdown表格。

huangapple go评论114阅读模式
英文:

How can I turn a dataframe into a markdown vertical table?

问题

  1. 编辑回答
  2. 我需要两种类型的表格一种是常规的水平表格视图为此我只是使用了to_markdown()并添加了代码以删除索引
  3. 对于垂直视图我复制并粘贴了下面的Ehsan的代码它完美地运行了
  4. 现在我想将这些粘贴到我的Excel表中以获得一个良好的视图这将需要大量的工作和特定的格式而且无法使用to_markdown()因为它会将DataFrame更改为字符串要将其作为索引获取您不能使用该函数您要么必须使用现有的DataFrame并找出如何添加新行和列要么创建一个具有正确数量的列和行的空DataFrame并使用必要的|格式进行填充之后您必须使用包含数据的DataFrame填充空/正确的单元格但是这太麻烦了所以我直接将字符串复制到正确的Excel表中使用以下代码
  5. ```python
  6. #现在我们将保存此循环的迭代到正确的Excel表中
  7. file_source ='Source Used.xlsx'
  8. #加载Excel文件
  9. workbook = load_workbook(filename=file_source)
  10. #选择表“Sheet Used”
  11. ws4 = workbook["Project X"]
  12. #修改所需的单元格
  13. ws4.cell(row = 1, column = 1).value = newDataFrameWithStringFormat
  14. #保存文件
  15. workbook.save(filename=file_source)

从这里开始,每当我想要更新我的Markdown网站时,我只需从Excel表的第一个单元格中提取。它看起来不漂亮,但它有效。

编辑结束

  1. <details>
  2. <summary>英文:</summary>
  3. EDIT Answer:
  4. There are two types of tables I needed. One was the regular Horizontal table view. For that, I just used the &quot;to_markdown()&quot; with the added code to removed the indeces.
  5. For the vertical view I copied and pasted Ehsan&#39;s code below and it worked perfectly.
  6. Now, I wanted to paste these in a nice view to my excel sheet. That would have taken a bunch of work and formatting very specifically, and it won&#39;t work out with the to_markdown(), since that changes the DataFrame to a string. To get it as an index, you can&#39;t use that function. You&#39;d either have to take your existing DataFrame and figure out how to add new rows and columns, or: create an empty DataFrame with the proper amount of columns and rows, and fill it with the necessary &quot;|&quot; formatting. After that, you&#39;d have to fill out the empty/correct cells with data from your DataFrame that contains the data. However, this is too much work, so instead I just copied the string over directly into the proper excel sheet using this code:

#Now we are going to save this loop's iteration into the proper Excel sheet
file_source ='Source Used.xlsx'

  1. #load excel file
  2. workbook = load_workbook(filename=file_source)
  3. #Pick the sheet &quot;Sheet Used&quot;
  4. ws4 = workbook[&quot;Project X&quot;]
  5. #modify the desired cell
  6. ws4.cell(row = 1, column = 1).value = newDataFrameWithStringFormat
  7. #save the file
  8. workbook.save(filename=file_source)
  1. From here, anytime I wanted to update my markdown website, I could just pull from the Excel sheet&#39;s first cell. It doesn&#39;t look pretty, but it works.
  2. END EDIT
  3. --------------------------------------------
  4. I have a table that looks like this:
  5. df:
  6. | Project 1 | Project 2 | Project 3 |
  7. |:---- |:------:| -----:|
  8. | data 1 | data 2 | data 3 |
  9. | data 4 | data 5 | data 6 |
  10. |data 7 |data 8 | data 9 |
  11. I want to edit this table so that it can work with, say, markdown, and be formatted well. However, to do that, I need to add a bunch of formatting to it (it basically needs to look the same as StackOverflow&#39;s table setup when writing this question). What function can I apply to it so that a new table is created that looks like this:
  12. [![Table with headers on the rows][1]][1]
  13. As you can see in this picture, the pipes and hyphens are each a new cell of data. Additionally, the Column HEADERS are at the beginning of the rows, since this is a horizontal format. How can I apply this formatting to dataframes of varying size?
  14. This is what the new one should look like (I bolded the Project names myself): [![enter image description here][2]][2]
  15. Now hypothetically, I can transpose the data and use to_markdown(), but that may still run into the issue of the top column being created as a column header. How can I avoid this by making a custom function to add in the pipes (&quot;|&quot;) and hyphens?
  16. Thank you!
  17. [1]: https://i.stack.imgur.com/uTDVs.png
  18. [2]: https://i.stack.imgur.com/2jWiF.png
  19. </details>
  20. # 答案1
  21. **得分**: 2
  22. 以下是代码的翻译部分:
  23. ```python
  24. import pandas as pd
  25. df=pd.DataFrame({"Project 1":["data 1", "data 4", "data 7"], "Project 2": ["data 2", "data 5", "data 8"], "Project 3": ["data 3", "data 6", "data 9"]})
  26. df = df.transpose()
  27. # 移除标题
  28. df.columns = ["" for i in range(len(df.columns))]
  29. # 使索引加粗 - ** **
  30. df.index = ["**{}**".format(idx) for idx in df.index]
  31. print(df.to_markdown())
  32. #| | | | |
  33. #|:--------------|:-------|:-------|:-------|
  34. #| **Project 1** | data 1 | data 4 | data 7 |
  35. #| **Project 2** | data 2 | data 5 | data 8 |
  36. #| **Project 3** | data 3 | data 6 | data 9 |

如果您需要指定格式的Markdown表格的CSV版本,您可以修改字符串并将其保存为CSV文件:

  1. markdown_text = df.to_markdown() # 来自上述代码
  2. markdown_csv = markdown_text.replace("|", ",|,").replace(",\n,", "\n")
  3. with open("results.csv", "w", encoding="utf-8") as fp:
  4. fp.write(markdown_csv)

结果将如下所示(如果您不需要**{}**,Markdown加粗,请注释掉代码的那部分):

你可以将一个数据框转换成一个垂直排列的Markdown表格。

英文:

A potential answer:

  1. import pandas as pd
  2. df=pd.DataFrame({&quot;Project 1&quot;:[&quot;data 1&quot;, &quot;data 4&quot;, &quot;data 7&quot;], &quot;Project 2&quot;: [&quot;data 2&quot;, &quot;data 5&quot;, &quot;data 8&quot;], &quot;Project 3&quot;: [&quot;data 3&quot;, &quot;data 6&quot;, &quot;data 9&quot;]})
  3. df = df.transpose()
  4. # remove header
  5. df.columns = [&quot;&quot; for i in range(len(df.columns))]
  6. # make the index bold - ** **
  7. df.index = [&quot;**{}**&quot;.format(idx) for idx in df.index]
  8. # **Project 1** data 1 data 4 data 7
  9. # **Project 2** data 2 data 5 data 8
  10. # **Project 3** data 3 data 6 data 9
  11. print(df.to_markdown())
  12. #| | | | |
  13. #|:--------------|:-------|:-------|:-------|
  14. #| **Project 1** | data 1 | data 4 | data 7 |
  15. #| **Project 2** | data 2 | data 5 | data 8 |
  16. #| **Project 3** | data 3 | data 6 | data 9 |

Will be like this:

Project 1 data 1 data 4 data 7
Project 2 data 2 data 5 data 8
Project 3 data 3 data 6 data 9

Updated:

In case you want the csv version of the markdown table in your specified format, you can modify the string and save it as a csv file:

  1. markdown_text = df.to_markdown() # from above code
  2. markdown_csv= markdown_text.replace(&quot;|&quot;, &quot;,|,&quot;)[1:-1].replace(&quot;,\n,&quot;,&quot;\n&quot;)
  3. with open(&quot;results.csv&quot;, &quot;w&quot;, encoding=&quot;utf-8&quot;) as fp:
  4. fp.write(markdown_csv)

The results will be (you can skip **{}**, markdown bold, in case you don't want it - just comment that part of the code):
你可以将一个数据框转换成一个垂直排列的Markdown表格。

huangapple
  • 本文由 发表于 2023年7月6日 21:53:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76629588.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定