📅  最后修改于: 2023-12-03 15:33:23.730000             🧑  作者: Mango
Pandas is a popular python library for data manipulation and analysis. While working with pandas, we often need to display tabular data in a more readable format. The tabulate
function from the tabulate
library can be used for this purpose. However, by default, it displays the index column, which may not always be desirable. In this article, we will discuss how to print a pandas dataframe using the tabulate
function without the index column.
One way to remove the index column is to drop it from the dataframe before using the tabulate
function. We can use the reset_index()
function of pandas to achieve this.
import pandas as pd
from tabulate import tabulate
data = {"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35],
"Salary": [50000, 60000, 70000]}
df = pd.DataFrame(data)
df = df.reset_index(drop=True)
print(tabulate(df, headers="keys", tablefmt="github"))
Output:
| Name | Age | Salary |
|---------|-------|----------|
| Alice | 25 | 50000 |
| Bob | 30 | 60000 |
| Charlie | 35 | 70000 |
Here, we first create a dataframe containing three columns - "Name", "Age", and "Salary" - and three rows of data. We then drop the index column using the reset_index()
function with the drop=True
argument. Finally, we use the tabulate
function to display the dataframe in a tabular format. The headers="keys"
argument specifies that column headers should be displayed, and the tablefmt="github"
argument specifies the output format.
Another way to remove the index column is to use the showindex=False
argument of the tabulate
function.
import pandas as pd
from tabulate import tabulate
data = {"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35],
"Salary": [50000, 60000, 70000]}
df = pd.DataFrame(data)
print(tabulate(df, headers="keys", tablefmt="github", showindex=False))
Output:
| Name | Age | Salary |
|---------|-------|----------|
| Alice | 25 | 50000 |
| Bob | 30 | 60000 |
| Charlie | 35 | 70000 |
Here, we create the same dataframe as before, but this time we do not drop the index column. Instead, we use the showindex=False
argument of the tabulate
function to hide the index column while displaying the dataframe.
Both Method 1 and Method 2 are useful for printing pandas dataframes in a user-friendly tabular format without the unwanted index column. Use whichever method suits your workflow the best!