[英]How to aligne text in a table using HTML in a Jupyter Notebook markdown cell?
[英]How can I test a table written in Markdown with Python? (using Jupyter Notebook)
假設我在 Jupyter Notebook 的 Markdown 單元格中有一張表:
| Attr1 | Attr2 |
| :---: | :---: |
| Val11 | Val21 |
| Val12 | Val22 |
現在我想測試(在 Python 中)此表中的值是否正確。 也就是說,如果 Attr1 = x,Attr2 = y,Val11 = x1,Val21 = y1,Val12 = x2,Val22 = y2。 有什么辦法可以將表鍵入 python 中的字符串,然后將字符串拆分為相關的單詞,然后遍歷列表? 提前致謝。
這有點復雜,但您可以將StringIO
與pandas
read_csv
一起使用。 基本上將您的標記表更改為 csv 並將其加載到 dataframe 中。這樣您就可以對 dataframe 執行各種操作:
from io import StringIO
import pandas as pd
md_table_str = """| Attr1 | Attr2 |
| :---: | :---: |
| Val11 | Val21 |
| Val12 | Val22 |"""
table_csv = ""
for line in md_table_str.split('\n'):
table_csv += line.strip('|') + '\n'
df = pd.read_csv(StringIO(table_csv), sep=' | ', engine="python")
print(df.drop(0)) # deleting first row (:---:)
Output:
Attr1 | Attr2
1 Val11 | Val21
2 Val12 | Val22
除其他事項外,您還可以訪問單元格值:
print(df.at[1, 'Attr1'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.