0

I am trying to use tabulate to print rows of a pandas DataFrame one at a time on a file. Only the first printing needs the headers, the other rows printed need the same spacing as the first row but no headers printed. Is this achievable with simple tabulate syntax for printing?

Here is a snippet code of the idea:

index = 0
with open('texttest.txt', 'w') as f:
    for state in states[:3]:
        if index == 0:
            f.write(tabulate(transition_df, headers='keys', tablefmt='psql', showindex=False ))
            index += 1 
        else:
            f.write(tabulate(transition_df, tablefmt='psql', showindex=False ))

prints this:

+---------+----------+----------+--------+--------+------+----------+-----------+-----------------+-----------------+--------------------+----------+----------+---------------+---------------+------------------+---------+--------+
|   State |   Energy |   OscStr |   Spin |   From |   To |    Coeff |   SqCoeff |   MO_index_FROM | AtomType_FROM   |   AtomContrib_FROM |   S_FROM |   P_FROM |   MO_index_TO | AtomType_TO   |   AtomContrib_TO |    S_TO |   P_TO |
|---------+----------+----------+--------+--------+------+----------+-----------+-----------------+-----------------+--------------------+----------+----------+---------------+---------------+------------------+---------+--------|
|       1 |   5.2455 |   0.1416 |      0 |    232 |  244 | -0.23232 | 0.0539726 |             232 | Cl              |              0.784 |  -0.0012 |   0.7852 |           244 | Cs            |           0.6231 | -0.5379 |  1.161 |
+---------+----------+----------+--------+--------+------+----------+-----------+-----------------+-----------------+--------------------+----------+----------+---------------+---------------+------------------+---------+--------++---+--------+--------+---+-----+-----+---------+-----------+-----+----+-------+---------+--------+-----+----+--------+--------+--------+
| 2 | 5.3137 | 2.1694 | 0 | 232 | 249 | 0.30159 | 0.0909565 | 232 | Cl | 0.784 | -0.0012 | 0.7852 | 249 | Pb | 0.5911 | 0.0008 | 0.5903 |
+---+--------+--------+---+-----+-----+---------+-----------+-----+----+-------+---------+--------+-----+----+--------+--------+--------++---+--------+--------+---+-----+-----+---------+-----------+-----+----+-------+---------+--------+-----+----+--------+--------+--------+
| 3 | 5.3341 | 1.7602 | 0 | 232 | 233 | 0.21276 | 0.0452668 | 232 | Cl | 0.784 | -0.0012 | 0.7852 | 233 | Cs | 0.9384 | 0.7359 | 0.2025 |
+---+--------+--------+---+-----+-----+---------+-----------+-----+----+-------+---------+--------+-----+----+--------+--------+--------+

I would like the same spacing as the headers but not print the headers in the file.

I have worked out a solution where I generate the dataframe first and then print it, but I want to know if this is possible to do on the fly like I wanted to do here initially.

Ernek
  • 3
  • 5
  • first you should add `write("\n")` when you write it - to start next row in new line. – furas Oct 14 '22 at 23:44
  • 1
    You could first generate table with headers in text variable, and next remove first 2-3 rows from variable and later write it. But it may still have problem if new data are longer than old data. Maybe you should rather write all at once. – furas Oct 14 '22 at 23:46

1 Answers1

0
temp_df = states.copy()

# Add a bit of padding for future values:
extra_space = 4
temp_df.columns = [x.center(len(x) + extra_space) for x in temp_df.columns]

# Get just the header.
header = '\n'.join(temp_df.iloc[:0].to_markdown(tablefmt='psql', index=False).splitlines()[:3])

with open('texttest.txt', 'w') as f:
    # write the header to file:
    f.write(header + '\n')
    # For each row that you want, 
    # make a new output with just that row.
    # Then cut the header off.
    for row in range(len(temp_df[:3])):
        lines = '\n'.join(temp_df.iloc[[row]].to_markdown(tablefmt='psql', index=False).splitlines()[3:])
        # Write the row to file.
        f.write(lines + '\n')

Output:

+-------------+--------------+--------------+------------+------------+----------+-------------+---------------+---------------------+---------------------+------------------------+--------------+--------------+-------------------+-------------------+----------------------+------------+
|   State     |   Energy     |   OscStr     |   Spin     |   From     |   To     |   Coeff     |   SqCoeff     |   MO_index_FROM     |   AtomType_FROM     |   AtomContrib_FROM     |   S_FROM     |   P_FROM     |   MO_index_TO     |   AtomType_TO     |   AtomContrib_TO     |   S_TO     |
|-------------+--------------+--------------+------------+------------+----------+-------------+---------------+---------------------+---------------------+------------------------+--------------+--------------+-------------------+-------------------+----------------------+------------|
|           1 |       5.2455 |       0.1416 |          0 |        232 |      244 |    -0.23232 |     0.0539726 |                 232 | Cl                  |                  0.784 |      -0.0012 |       0.7852 |               244 | Cs                |               0.6231 |    -0.5379 |
+-------------+--------------+--------------+------------+------------+----------+-------------+---------------+---------------------+---------------------+------------------------+--------------+--------------+-------------------+-------------------+----------------------+------------+
|           2 |       5.3137 |       2.1694 |          0 |        232 |      249 |     0.30159 |     0.0909565 |                 232 | Cl                  |                  0.784 |      -0.0012 |       0.7852 |               249 | Pb                |               0.5911 |     0.0008 |
+-------------+--------------+--------------+------------+------------+----------+-------------+---------------+---------------------+---------------------+------------------------+--------------+--------------+-------------------+-------------------+----------------------+------------+
|           3 |       5.3341 |       1.7602 |          0 |        232 |      233 |     0.21276 |     0.0452668 |                 232 | Cl                  |                  0.784 |      -0.0012 |       0.7852 |               233 | Cs                |               0.9384 |     0.7359 |
+-------------+--------------+--------------+------------+------------+----------+-------------+---------------+---------------------+---------------------+------------------------+--------------+--------------+-------------------+-------------------+----------------------+------------+
BeRT2me
  • 12,699
  • 2
  • 13
  • 31
  • This works. I added numalign='center and stralign='center' arguments in the calls to .to_markdown for better formatting of the output. Note: states is not the df, transition_df.copy() should be the first line. – Ernek Oct 17 '22 at 16:53