首页 文章

带字符串列名的DataFrame

提问于
浏览
1

我有以下问题:我构造了一个带有整数列名和周期索引的DataFrame . 现在,如果我使用以下函数重命名列:df.rename(columns = lambda x:str(x),inplace = True)

因此,我将列的类型转换为字符串我观察到以下奇怪的行为:在操作之前,如果我从框架中检索一列,我得到了一个系列 . 现在,在某些列上我获得了一个DataFrame:以前df.loc [:,1]给出了一个系列:

现在,df.loc [:,'1']给出一个DataFrame,其PeriodIndex的长度为0,完整的原始列为df .

有没有人知道我做错了什么或者我偶然发现了一个错误?

这是一个代码片段,它重现了bug(?):

A = pd.DataFrame(dict(zip(range(0,9000), [pd.Series([1,2,3], [pd.Period(1), pd.Period(2), pd.Period(3)]) for x in range(0,9000)])))

A[5000]
A.rename(columns = lambda x: str(x), inplace=True)

A['5000'] # This should return a DataFrame with a zero-PeriodIndex and the full columns!

非常感谢您提前和最好的问候马克

1 回答

  • 1

    这是掌握 . 看起来不错

    In [11]: A = pd.DataFrame(dict(zip(range(0,9000), [pd.Series([1,2,3], [pd.Period(1), pd.Period(2), pd.Period(3)]) for x in range(0,9000)])))
    
    In [12]: A['5000']
    Out[12]: 
    <class 'pandas.core.frame.DataFrame'>
    PeriodIndex: 0 entries
    Columns: 9000 entries, 0 to 8999
    dtypes: int64(9000)
    
    In [13]: A[5000]
    Out[13]: 
    1-01-01    1
    1-01-02    2
    1-01-03    3
    Freq: D, Name: 5000, dtype: int64
    
    In [14]: A.rename(columns = lambda x: str(x), inplace=True)
    
    In [15]: A['5000']
    Out[15]: 
    1-01-01    1
    1-01-02    2
    1-01-03    3
    Freq: D, Name: 5000, dtype: int64
    
    In [16]: A[5000]
    KeyError: u'no item named 5000'
    

相关问题