Одинаковый код DataFrame.reindex - другой вывод - PullRequest
1 голос
/ 11 марта 2019

Добрый день всем,

Я хочу отфильтровать из DataFrame столбцы, которые мне не интересны. Для этого - и так как столбцы могут меняться в зависимости от ввода пользователя (который я не буду показыватьздесь) - я использую следующий код в моей функции offshore_filter:

# Note: 'df' is my DataFrame, with different country codes as rows and years as columns' headers

import datetime as d
import pandas as pd

COUNTRIES = [
        'EU28', 'AL', 'AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'EL',
        'ES', 'FI', 'FR', 'GE', 'HR', 'HU', 'IE', 'IS', 'IT', 'LT', 'LU', 'LV',
        'MD', 'ME', 'MK', 'MT', 'NL', 'NO', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK',
        'TR', 'UA', 'UK', 'XK'

YEARS = list(range(2005, int(d.datetime.now().year)))

def offshore_filter(df, countries=COUNTRIES, years=YEARS):
    # This function is specific for filtering out the countries
    # and the years not needed in the analysis

    # Filter out all of the countries not of interest
    df.drop(df[~df['country'].isin(countries)].index, inplace=True)

    # Filter out all of the years not of interest
    columns_to_keep = ['country', 'country_name'] + [i for i in years]
    temp = df.reindex(columns=columns_to_keep)
    df = temp  # This step to avoid the copy vs view complication

    return df

Когда я передаю список years целых чисел, код работает хорошо и фильтрует DataFrame, принимая только столбцы всписок years.

Однако, если заголовки столбцов DataFrame являются строками (например, '2018' вместо 2018), изменение [i for i in years] на [str(i) for i in years] не работает, и у меня есть столбцыНана (как гласит документация reindex ).

Можете ли вы помочь мне определить, почему?

...