1
\$\begingroup\$

Please download the file and save in home directory and extract it:

https://www.dropbox.com/s/swtw8bk35zr1i6d/analyse.7z?dl=0

I can get some warrants info.

import analyse
df = analyse.warrants.get('0788')

Now we got 0788's warrants info. It output df with better format:

analyse.tabulate.tabulate(df)

I want to simply the expression as df.tabulate(). How do I refactor the code in analyse directory?

Show content in tabulate.py:

import pandas as pd
from terminaltables import AsciiTable   

def tabulate(df):
    rows = len(df)
    head = [df.columns.tolist()]
    nr = df.values.tolist()
    content = head + nr
    table = AsciiTable(content)
    data_str = table.table.split('\n')
    sep_line = data_str[0]
    transformed_str = []
    for ind in range(0,len(data_str)-1):
        if ind < 3 :
            transformed_str.append(data_str[ind])
        else:
            transformed_str.append(data_str[ind])
            transformed_str.append(sep_line)
    new_str = "\n".join(transformed_str) + '\n' + '\n'  + '[ {} records ]'.format(rows-1)
    print(new_str)

I want to refactor analyse.tabulate.tabulate(df) as df.tabulate(). It is the simplest way to use df.tabulate() to get well-formatted dataframe.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I honestly have no idea what you're asking. You want to simplify your tabulate method? \$\endgroup\$
    – Reinderien
    Commented Mar 24, 2020 at 14:37
  • \$\begingroup\$ I want to refactor analyse.tabulate.tabulate(df) as df.tabulate(). It is simple to use df.tabulate() to get well-formatted dataframe. \$\endgroup\$
    – showkey
    Commented Mar 24, 2020 at 15:35

1 Answer 1

1
\$\begingroup\$

This if statement

    if ind < 3 :
        transformed_str.append(data_str[ind])
    else:
        transformed_str.append(data_str[ind])
        transformed_str.append(sep_line)

Can be rewritten as

    transformed_str.append(data_str[ind])
    if ind >= 3:
        transformed_str.append(sep_line)
\$\endgroup\$
1
  • \$\begingroup\$ Not to simplify tabulate method ,the citation way analyse.tabulate.tabulate(df) is too long to write,i want to get same result with df.tabulate(). \$\endgroup\$
    – showkey
    Commented Mar 24, 2020 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.