[英]Wrapping column names in Python Pandas DataFrame or Jupyter Notebooks
我的數據框中某些列的標題很長,我希望能夠對文本進行換行。 我知道這個功能內置於 pandas 中,就像我一樣:
pd.DataFrame(np.random.randn(2, 10),
columns=['Very Long Column Title ' + str(i) for i in range(10)])
但如果我的列數較少,標題將不會換行:
pd.DataFrame(np.random.randn(10, 2),
columns=['Very Long Column Title ' + str(i) for i in range(2)])
我還嘗試手動插入換行符:
import pandas as pd
pd.DataFrame(np.random.randn(10, 2),
columns=['Very Long \n Column Title ' + str(i) for i in range(2)])
但這給出了與上面相同的 output。
我在這個主題上找到了類似的答案:
我在 Jupyter notebook 上工作,但如果可能的話,我更喜歡基於 pandas 的解決方案。
Jupyter筆記本從許多來源繼承了它們的顯示屬性。 pandas
中沒有屬性限制列標題的寬度,因為pandas
不是導致文本換行的原因,它實際上是呈現的HTML。
您可以使用以下方法覆蓋默認的Jupyter Notebook樣式以限制表頭的最大寬度:
from IPython.core.display import HTML
HTML("<style>.rendered_html th {max-width: 120px;}</style>")
在筆記本頂部運行此代碼一次,將html表頭的最大列寬設置為120像素。
這是一個不涉及更改IPython屬性的答案:
df = pd.DataFrame(np.random.randn(10, 2),
columns=['Very Long Column Title ' + str(i) for i in range(2)])
df.style.set_table_styles([dict(selector="th",props=[('max-width', '50px')])])
或者,您可以使用 package textwrap
:
import textwrap
cols = ['Very Long Column Title ' + str(i) for i in range(2)]
# Split wide columns, you can then join these with any delimiter you'd like
cols = [textwrap.wrap(x, width=20) for x in cols]
# print(cols)
# [['Very Long Column', 'Title 0'], ['Very Long Column', 'Title 1']]
您可以通過在列標題中插入空格來“入侵”正確的行為:
def colfix(df, L=5): return df.rename(columns=lambda x: ' '.join(x.replace('_', ' ')[i:i+L] for i in range(0,len(x),L)) if df[x].dtype in ['float64','int64'] else x )
colfix(your_df)
請參閱我對類似問題的回答https://stackoverflow.com/a/45078833/6903458
無論您是否使用 Jupyter,@AndreyF 的答案版本都有效。 該例程使用 Pandas 樣式器將 dataframe 呈現為 HTML。然后要查看表格,您必須將 HTML 保存到文件並在瀏覽器中打開它。 請注意,樣式器被顯式捕獲為變量。
df = pd.DataFrame(np.random.randn(10, 2),
columns=['Very Long Column Title ' + str(i) for i in range(2)])
styler = df.style.set_table_styles([dict(selector="th",props=[('max-width', '50px')])])
with open("/tmp/testStyle.html",'w') as f: f.write(styler.render())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.