Сводная таблица Pandas: ошибка типа: ‘<' не поддерживается между экземплярами 'CustomFieldOption' и 'CustomFieldOption'

#python #pandas

#python #pandas

Вопрос:

Я извлекаю данные из внутренней базы данных, сохраняю их как фрейм данных Pandas, затем поворачиваю фрейм данных. Я получаю сообщение об ошибке, которое, по-видимому, связано с различиями в типах данных. Я потратил часы, пытаясь отладить это, но безуспешно. Вот полный код:

 from jira import JIRA
import pandas as pd

cert_path = 'C:\cert.crt'

start_date = '2020-10-01'
end_date = '2020-10-31'

# three different instances (each with their own schema)
a_session = JIRA(server='https://jira.myinstance-A.com', options={'verify': cert_path}, kerberos=True)

b_session = JIRA(server='https://jira.myinstance-B.com', options={'verify': cert_path}, kerberos=True)

c_session = JIRA(server='https://jira.myinstance-C.com', options={'verify': cert_path}, kerberos=True)


# define Jira queries
query_1 = 'project = "Test Project 1" and issuetype = Incident and resolution = Resolved and updated >= {} and updated <= {}'.format(start_date, end_date)

query_2 = 'project = "Test Project 2" and issuetype = Incident and resolution = Resolved and updated >= {} and updated <= {}'.format(start_date, end_date)

query_3 = 'project = "Test Project 3" and issuetype = Defect and resolution = Resolved and releasedate >= {} and releasedate <= {}'.format(start_date, end_date)

query_4 = 'project = "Test Project 4" and issuetype = Enhancement and resolution = Done and completed >= {} and completed <= {}'.format(start_date, end_date)


# fetch all issues from a given session for a given query
block_size = 100
block_num = 0


def get_all_issues(session, query):

    block_size = 50
    block_num = 0
    
    start = 0
    all_issues = []
    while True:
        issues = session.search_issues(query, start, block_size)
        if len(issues) == 0:
            # No more issues
            break
        start  = len(issues)
        for issue in issues:
            all_issues.append(issue)

    issues = pd.DataFrame(issues)

    for issue in all_issues:
        d = {
            'jira_key' : issue.key,
            'issue_type' : issue.fields.type,
            'creator' : issue.fields.creator,
            'resolution' : issue.fields.resolution
             }

        fields = issue.fields  # For brevity
        if hasattr(fields, "custom_field_123"):
            d['system_change'] = fields.custom_field_123
        if hasattr(fields, "custom_field_456"):
            d['system_resources'] = fields.custom_field_456
        if hasattr(fields, "custom_field_789"):
            d['system_backup'] = fields.custom_field_789

        issues = issues.append(d, ignore_index=True)

    return issues


# list of queries, and the corresponding backend
queries = [
    (a_session, query_1),
    (a_session, query_2),
    (b_session, query_3),
    (c_session, query_4),
]


# loop over each pair of session and query, calling the get_all_issues function, and save the dataframe we get each time
dataframes = []

for session, query in queries:
    dataframe = get_all_issues(session, query)
    dataframes.append(dataframe)


# concatenate all data frames
df_concat = pd.concat(dataframes)

# derive the business units from the project codes
df_concat['business_unit'] = np.where(df_concat['jira_key'].str.contains('MER'), 'Mercedes',
                             np.where(df_concat['jira_key'].str.contains('HON'), 'Honda',
                             np.where(df_concat['jira_key'].str.contains('AST'), 'Aston Martin', '*ERROR*')))
  

Фрейм df_concat данных выводится следующим образом:

    jira key   issue_type    creator   resolution   system_change   system_resources   system_backup   business_unit
0  MER-361    Incident      Smith, J  Resolved     Saturn          High               NaN             Mercedes
1  MER-362    Enhancement   Jones, T  In Progress  NaN             Medium             Not Applicable  Mercedes
2  MER-363    Incident      Ng, V     Resolved     Saturn          NaN                Not Applicable  Mercedes
3  MER-364    Incident      Jones, T  Resolved     NaN             NaN                Not Applicable  Mercedes
0  AST-022    Incident      Smith, J  Resolved     Saturn          High               NaN             Astin Martin
1  AST-023    Incident      Smith, J  Resolved     Saturn          High               NaN             Astin Martin
2  AST-024    Incident      Jones, T  Resolved     Saturn          High               NaN             Astin Martin
0  HON-124    Incident      Smith, J  In Progress  NaN             Low                NaN             Honda
1  HON-125    Incident      Smith, J  Resolved     Saturn          High               NaN             Honda
2  HIN-126    Incident      Jones, T  In Progress  Saturn          Low                NaN             Honda
  

Обратите внимание, как изменяется индекс во фрейме данных.

Цель состоит в том, чтобы применить сводную таблицу Pandas к фрейму df_concat данных:

 # first, fill replace all of the Nan values with empty strings:
df_all = df_all.fillna('')


# then, ensure the columns are cast to strings   
df_concat['business_unit'].astype('str')
df_concat['system_change'].astype('str')


# finally, pivot the data
pivot = pd.pivot_table(data=df_concat, index='business_unit', columns='system_change'), values='jira_key, aggfunc='size')

pivot
  

Я вижу следующее сообщение об ошибке:

 TypeError: '<' not supported between instances of 'CustomFieldOption' and 'CustomFieldOption' 
  

Я подумал, что, возможно, ошибка связана с пользовательскими полями. Но, похоже, это не так.

Я тестировал со следующим:

Тест # 1:

 pivot = pd.pivot_table(data=df_concat, index='creator', columns='issue_type'), values='jira_key, aggfunc='size')
  

Приводит к:

 TypeError: '<' not supported between instances of 'User' and 'User'
  

Тест # 2:

 pivot = pd.pivot_table(data=df_concat, index='creator', columns='issue_type'), values='jira_key, aggfunc='size')
  

Приводит к:

 TypeError: '<' not supported between instances of 'User' and 'User'
  

Тест # 3:

 pivot = pd.pivot_table(data=df_concat, index='resolution', columns='issue_type'), values='jira_key, aggfunc='size')
  

Приводит к:

 TypeError: '<' not supported between instances of 'Resolution' and 'Resolution'
  

Тест # 4:

 pivot = pd.pivot_table(data=df_concat, index='creator', columns='resolution'), values='jira_key, aggfunc='size')
  

Приводит к:

 TypeError: '<' not supported between instances of 'User' and 'User'
  

Я заменил все NaN значения пустыми строками и преобразовал столбцы business_unit and system_changes в строки.

Для производственных данных я также выполнил следующее:

 from sklearn import preprocessing

encoder = preprocessing.LabelEncoder()
encoder.fit_transform(df_all['creator'].astype(str))
encoder.fit_transform(df_all['resolution'].astype(str))
  

Я вижу:

 array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]
  

Я не уверен, почему возникает эта '<' not supported between instances of... ошибка. Возможно, есть проблема с индексом (он запускается заново каждый раз, когда фрейм данных объединяется), но я не уверен, как это отладить дальше. Любая помощь была бы очень признательна.

Заранее спасибо!