[英]How to print pandas DataFrame without index
我想打印整個數據框,但我不想打印索引
此外,一列是日期時間類型,我只想打印時間,而不是日期。
數據框看起來像:
User ID Enter Time Activity Number
0 123 2014-07-08 00:09:00 1411
1 123 2014-07-08 00:18:00 893
2 123 2014-07-08 00:49:00 1041
我希望它打印為
User ID Enter Time Activity Number
123 00:09:00 1411
123 00:18:00 893
123 00:49:00 1041
print df.to_string(index=False)
print(df.to_string(index=False))
打印時,下面的行將隱藏 DataFrame 的索引列
df.style.hide_index()
更新:用 Python 3.7 測試
print(df.to_csv(sep='\t', index=False))
或者可能:
print(df.to_csv(columns=['A', 'B', 'C'], sep='\t', index=False))
如果你想漂亮地打印數據框,那么你可以使用tabulate包。
import pandas as pd
import numpy as np
from tabulate import tabulate
def pprint_df(dframe):
print tabulate(dframe, headers='keys', tablefmt='psql', showindex=False)
df = pd.DataFrame({'col1': np.random.randint(0, 100, 10),
'col2': np.random.randint(50, 100, 10),
'col3': np.random.randint(10, 10000, 10)})
pprint_df(df)
具體來說, showindex=False
,顧名思義,允許您不顯示索引。 輸出將如下所示:
+--------+--------+--------+
| col1 | col2 | col3 |
|--------+--------+--------|
| 15 | 76 | 5175 |
| 30 | 97 | 3331 |
| 34 | 56 | 3513 |
| 50 | 65 | 203 |
| 84 | 75 | 7559 |
| 41 | 82 | 939 |
| 78 | 59 | 4971 |
| 98 | 99 | 167 |
| 81 | 99 | 6527 |
| 17 | 94 | 4267 |
+--------+--------+--------+
如果您只想打印字符串/json,可以使用以下方法解決:
print(df.to_string(index=False))
Buf 如果您也想序列化數據甚至發送到 MongoDB,最好執行以下操作:
document = df.to_dict(orient='list')
現在有 6 種方法可以定位數據,請在更適合您的panda 文檔中查看更多信息。
要回答“如何在沒有索引的情況下打印數據幀”問題,您可以將索引設置為空字符串數組(數據幀中的每一行一個),如下所示:
blankIndex=[''] * len(df)
df.index=blankIndex
如果我們使用您帖子中的數據:
row1 = (123, '2014-07-08 00:09:00', 1411)
row2 = (123, '2014-07-08 00:49:00', 1041)
row3 = (123, '2014-07-08 00:09:00', 1411)
data = [row1, row2, row3]
#set up dataframe
df = pd.DataFrame(data, columns=('User ID', 'Enter Time', 'Activity Number'))
print(df)
通常會打印為:
User ID Enter Time Activity Number
0 123 2014-07-08 00:09:00 1411
1 123 2014-07-08 00:49:00 1041
2 123 2014-07-08 00:09:00 1411
通過創建一個包含與數據框中行數一樣多的空字符串的數組:
blankIndex=[''] * len(df)
df.index=blankIndex
print(df)
它將從輸出中刪除索引:
User ID Enter Time Activity Number
123 2014-07-08 00:09:00 1411
123 2014-07-08 00:49:00 1041
123 2014-07-08 00:09:00 1411
在 Jupyter Notebooks 中將按照此屏幕截圖呈現: Juptyer Notebooks dataframe with no index column
任何在 Jupyter Notebook 上工作以打印沒有索引列的 DataFrame 的人,這對我有用:
display(table.hide_index())
與上面使用 df.to_string(index=False) 的許多答案類似,我經常發現有必要提取一列值,在這種情況下,您可以使用以下內容使用 .to_string 指定單個列:
data = pd.DataFrame({'col1': np.random.randint(0, 100, 10),
'col2': np.random.randint(50, 100, 10),
'col3': np.random.randint(10, 10000, 10)})
print(data.to_string(columns=['col1'], index=False)
print(data.to_string(columns=['col1', 'col2'], index=False))
它提供了一個易於復制(和無索引)的輸出,用於粘貼到其他地方(Excel)。 示例輸出:
col1 col2
49 62
97 97
87 94
85 61
18 55
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.