Python 相同的DataFrame.reindex代码-不同的输出

Python 相同的DataFrame.reindex代码-不同的输出,python,python-3.x,pandas,dataframe,reindex,Python,Python 3.x,Pandas,Dataframe,Reindex,各位下午好, 我想从数据框中筛选出我不感兴趣的列。 为了做到这一点,由于列可能会根据用户输入而改变(我将不在这里显示),我在我的offshore\u 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 = [

各位下午好,

我想从数据框中筛选出我不感兴趣的列。 为了做到这一点,由于列可能会根据用户输入而改变(我将不在这里显示),我在我的
offshore\u 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
整数列表时,代码运行良好,并通过只获取
years
列表中的列来过滤数据帧

但是,如果数据帧的列标题是字符串(例如,
'2018'
而不是
2018
),则将
[i for i in years]
更改为
[str(i)for i in years]
不起作用,并且我有Nan的列(如
reindex
所述)


你能帮我找出原因吗?

是否可以添加一个包含两行的示例数据集,以便我们可以进行自我测试?谢谢@erfan的回答。我在中上载了两个示例文件。注意:一个是纯Excel文件,另一个是TSV文件。不起作用的(例如,列标题为字符串的数据集)是TSV数据集。是否可以添加一个包含两行的示例数据集,以便我们自己进行测试?谢谢@erfan的回答。我在中上载了两个示例文件。注意:一个是纯Excel文件,另一个是TSV文件。不起作用的(例如,列标题为字符串的)是TSV。