Добавить текст в INT в Pandas DataFrame

+------------+-------------+-----------------------+------------------+-------------------+---------------+------------------------------+--------+
| Technology | All Backlog | All Backlog Completed | Percent Complete | Backlog Remaining | Internal ONLY | Ext/Int & Ready For External | Non-IC |
+------------+-------------+-----------------------+------------------+-------------------+---------------+------------------------------+--------+
| Tech 1     |        2395 |                  1069 | 44.63%           |              1326 |            34 |                          219 |    822 |
+------------+-------------+-----------------------+------------------+-------------------+---------------+------------------------------+--------+

Предполагая, что эта таблица является DataFrame ... (индекс удален)

Четыре правых столбца - это INT. Я хочу, чтобы они также отображали% завершено, как и в других столбцах, которые были отформатированы для отображения%. Такие как ...

+------------+-------------+-----------------------+------------------+-------------------+---------------+------------------------------+--------------+
| Technology | All Backlog | All Backlog Completed | Percent Complete | Backlog Remaining | Internal ONLY | Ext/Int & Ready For External |    Non-IC    |
+------------+-------------+-----------------------+------------------+-------------------+---------------+------------------------------+--------------+
| Tech 1     |        2395 |                  1069 | 44.63%           |              1326 | 34 (3.18%)    | 219 (20.48%)                 | 822 (76.89%) |
+------------+-------------+-----------------------+------------------+-------------------+---------------+------------------------------+--------------+

Я посмотрел на карту, карту применения и другие ... но единственное, что я смог понять, это:

+------------+-------------+-----------------------+------------------+-------------------+--------------------------------------+-----------------------------------------+----------------------------------------+
| Technology | All Backlog | All Backlog Completed | Percent Complete | Backlog Remaining |            Internal ONLY             |      Ext/Int & Ready For External       |                 Non-IC                 |
+------------+-------------+-----------------------+------------------+-------------------+--------------------------------------+-----------------------------------------+----------------------------------------+
| Tech 1     |        2395 |                  1069 | 44.63%           |              1326 | 34 (0 3.18% 1 3.18% dtype: float64%) | 219 (0 20.49% 1 20.49% dtype: float64%) | 822(0 76.89% 1 76.89% dtype: float64%) |
+------------+-------------+-----------------------+------------------+-------------------+--------------------------------------+-----------------------------------------+----------------------------------------+

Я понимаю, что это выглядит странно, потому что он пытается добавить серию к ячейке вместо соответствующих данных ... Следовательно, почему я ищу карту, но ничего из того, что я нашел, похоже, не соответствует потребности.

Вот код, с которым я сейчас работаю.

def get_IC_percomp(df:pd.DataFrame):
    """
    This function takes in the DF of the default view's data. 
    Takes the last 3 columns and divides by items completed. 
    (Checking for 0 to avoid math issues.) --- might not be possible since comparing DF columns

    Columns to perform this on:
        Internal ONLY
        Ext/Int & Ready For External
        Non-IC

    Returns a dictionary like:    {'Column Name': data_value, ...}

    """

    logger.debug('Starting get_IC_percomp()...')

    column_list = ['Internal ONLY', 'Ext/Int & Ready For External', 'Non-IC']
    new_dict = {column: None for column in column_list}    # could also do:  dict.fromkeys(keys, None)
    for col in column_list:
        #if float(df['All Backlog Completed'].applymap(float)) == 0.0:
        #    new_dict[col] = 0
        #else:
        #    new_dict[col] = df[col] / df['All Backlog Completed']
        new_dict[col] = df[col] / df['All Backlog Completed'] * 100

    logger.debug('Ending get_IC_percomp()...')
    return new_dict

def chg_font_fmt(data_dict:dict):
    """
    This function takes in a dictionary of data and returns 
    a dictionary for use in formatting the DataFrame.

    """

    new_dict = dict()
    new_dict['Percent Complete'] = '{:.2f}%'
    new_dict['Total Percent Complete'] = '{:.2f}%'
    new_dict['Historical Percent Complete'] = '{:.2f}%'
    new_dict['Sustain Percent Complete'] = '{:.2f}%'
    if data_dict is not None:
        new_dict['Internal ONLY'] = '{:}' + ' ({}%)'.format(data_dict['Internal ONLY'])
        new_dict['Ext/Int & Ready For External'] = '{:}' + ' ({}%)'.format(data_dict['Ext/Int & Ready For External'])
        new_dict['Non-IC'] = '{:}' + '({}%)'.format(data_dict['Non-IC'])

    return new_dict

percent_dict = None
if view_str.lower() == 'default':      # default view
    percent_dict = get_IC_percomp(df)

df.format(chg_font_fmt(percent_dict)).set_properties(**{'text-align': 'center'}).render()

Возможно, нашел здесь ответ: stackoverflow.com/a/54026256/10474024 Но тестирование не принесло результатов.

Найдите минутку, чтобы прочитать помощь при редактировании в справочном центре. Форматирование на Stack Overflow отличается от других сайтов. Чем лучше выглядит ваш пост, тем проще его прочитать и понять.

Patrick Artner 14.01.2019 22:43

Не знаете, как это должно что-то делать? Невозможно создать таблицу, поскольку таблица HTML не разрешена.

ProsperousHeart 14.01.2019 22:55

Ваши столбцы больше не будут оцениваться как int, а скорее как объект. Все хорошо?

d_kennetz 14.01.2019 23:39

Да, на данный момент он больше не должен быть int, так как я буду нажимать на HTML с помощью .render ()

ProsperousHeart 14.01.2019 23:50

Я считаю, что создал решение ... сейчас тестирую ... даст ответ, работает ли оно

ProsperousHeart 15.01.2019 00:10
Почему в Python есть оператор "pass"?
Почему в Python есть оператор "pass"?
Оператор pass в Python - это простая концепция, которую могут быстро освоить даже новички без опыта программирования.
Некоторые методы, о которых вы не знали, что они существуют в Python
Некоторые методы, о которых вы не знали, что они существуют в Python
Python - самый известный и самый простой в изучении язык в наши дни. Имея широкий спектр применения в области машинного обучения, Data Science,...
Основы Python Часть I
Основы Python Часть I
Вы когда-нибудь задумывались, почему в программах на Python вы видите приведенный ниже код?
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
Алиса и Боб имеют неориентированный граф из n узлов и трех типов ребер:
Оптимизация кода с помощью тернарного оператора Python
Оптимизация кода с помощью тернарного оператора Python
И последнее, что мы хотели бы показать вам, прежде чем двигаться дальше, это
Советы по эффективной веб-разработке с помощью Python
Советы по эффективной веб-разработке с помощью Python
Как веб-разработчик, Python может стать мощным инструментом для создания эффективных и масштабируемых веб-приложений.
0
5
141
1

Ответы 1

Требуется добавление новой функции map_perc - см. Код ниже.

def get_IC_percomp(df:pd.DataFrame):
    """
    This function takes in the DF of the default view's data. 
    Takes the last 3 columns and divides by items completed. 
    (Checking for 0 to avoid math issues.) --- might not be possible since comparing DF columns

    Columns to perform this on:
        Internal ONLY
        Ext/Int & Ready For External
        Non-IC

    Returns a dictionary like:    {'Column Name': data_value, ...}

    """

    logger.debug('Starting get_IC_percomp()...')

    column_list = ['Internal ONLY', 'Ext/Int & Ready For External', 'Non-IC']
    new_dict = {column: None for column in column_list}    # could also do:  dict.fromkeys(keys, None)
    for col in column_list:
        new_dict[col] = df[col] / df['All Backlog Completed'] * 100

    logger.debug('Ending get_IC_percomp()...')
    return new_dict

def chg_font_fmt(data_dict:dict):
    """
    This function takes in a dictionary of data and returns 
    a dictionary for use in formatting the DataFrame.

    """

    new_dict = dict()
    new_dict['Percent Complete'] = '{:.2f}%'
    new_dict['Total Percent Complete'] = '{:.2f}%'
    new_dict['Historical Percent Complete'] = '{:.2f}%'
    new_dict['Sustain Percent Complete'] = '{:.2f}%'
    if data_dict is not None:
        new_dict['Internal ONLY'] = '{:}' + ' ({}%)'.format(data_dict['Internal ONLY'])
        new_dict['Ext/Int & Ready For External'] = '{:}' + ' ({}%)'.format(data_dict['Ext/Int & Ready For External'])
        new_dict['Non-IC'] = '{:}' + '({}%)'.format(data_dict['Non-IC'])

    return new_dict

def map_perc(df:pd.DataFrame, data_dict:dict):
    """
    This function takes in a df and dictionary.
    Returns DF.

    """

    def use_idx_val(row):
        """
        https://stackoverflow.com/a/54026256/10474024

        """

        idx = row.name

        row['Internal ONLY'] = '{} ({:.2f}%)'.format(row['Internal ONLY'], data_dict['Internal ONLY'][idx])
        row['Ext/Int & Ready For External'] = '{} ({:.2f}%)'.format(row['Ext/Int & Ready For External'], data_dict['Ext/Int & Ready For External'][idx])
        row['Non-IC'] = '{} ({:.2f}%)'.format(row['Non-IC'], data_dict['Non-IC'][idx])

        return row

    df = df.apply(use_idx_val, axis=1)

    return df

percent_dict = None
if view_str.lower() == 'default':      # default view
    percent_dict = get_IC_percomp(df)
    df = map_perc(df, percent_dict)

df.format(chg_font_fmt(percent_dict)).set_properties(**{'text-align': 'center'}).render()

Другие вопросы по теме