Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Data Science by (17.6k points)

How can I print a pandas dataframe as a nice text-based table, like the following?

+------------+---------+-------------+

| column_one | col_two |   column_3  |

+------------+---------+-------------+

|          0 |  0.0001 | ABCD        |

|          1 |  1e-005 | ABCD        |

|          2 |  1e-006 | long string |

|          3 |  1e-007 | ABCD        |

+------------+---------+-------------+

1 Answer

0 votes
by (41.4k points)

You can use the .shape property. The shape property is usually used to get the current shape of an array, but may also be used to reshape the array in-place by assigning a tuple of array dimensions to it.

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: df = pd.DataFrame(np.arange(12).reshape(4,3))

In [4]: df

Out[4]: 

   0  1  2

0  0  1  2

1  3  4  5

2  6  7  8

3  9  10 11

In [5]: df.shape

Out[5]: (4, 3)

In [6]: timeit df.shape

2.77 µs ± 644 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [7]: timeit df[0].count()

348 µs ± 1.31 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [8]: len(df.index)

Out[8]: 4

In [9]: timeit len(df.index)

990 ns ± 4.97 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Related questions

Browse Categories

...