【问题标题】:Numbers used as string in Pandas indexPandas 索引中用作字符串的数字
【发布时间】:2016-09-04 18:41:35
【问题描述】:

我有以下文件:

Contract, FG
9896342,Y
11037874,Y
6912529,Y
9896652,N
363291,Y
7348524,Y
6078482,Y
7795457,N
2486242,Y
3297980,Y
9760560,Y
1200533,N
11033963,N
7861603,Y
8218268,Y
9760247,Y

我想从此文件创建一个 pandas DF 并将列 Contract 用作​​字符串或 unicode 索引列。它看起来像数字,但从技术上讲,它是一个字符串。

我这样做了:DF = pd.read_csv('C:\\Users\\S.Benet\\Desktop\\test.txt', index_col='Contract', dtype=object, encoding = 'utf-8')

但索引被解释为 INT。

>>DF.index
Int64Index([ 9896342, 11037874,  6912529,  9896652,   363291,  7348524,
             6078482,  7795457,  2486242,  3297980,  9760560,  1200533,
            11033963,  7861603,  8218268,  9760247],
           dtype='int64', name=u'Contract')

如何强制它成为字符串索引?

【问题讨论】:

    标签: string python-2.7 pandas


    【解决方案1】:

    如果你使用set_index而不是index_col,那么索引将包含字符串:

    df = pd.read_csv('data', dtype=object, encoding='utf-8')
    df = df.set_index('Contract')
    

    或者,等价的,

    df = pd.read_csv('data', dtype=object, encoding='utf-8').set_index('Contract')
    

    In [154]: df.info()
    <class 'pandas.core.frame.DataFrame'>
    Index: 16 entries, 9896342 to 9760247   # <-- a generic Index, not a Int64Index
    Data columns (total 1 columns):
     FG    16 non-null object
    dtypes: object(1)
    memory usage: 256.0+ bytes
    
    In [155]: df.index[0]
    Out[155]: '9896342'
    
    In [156]: type(df.index[0])
    Out[156]: str
    

    【讨论】:

    • 它工作 ^^ thx。有没有办法在一个命令行中做到这一点?还是我必须分两步完成?
    • 当然,它可以写成 1-liner:df = pd.read_csv('data', dtype=object, encoding='utf-8').set_index('Contract').
    猜你喜欢
    • 2019-10-29
    • 2020-10-20
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    相关资源
    最近更新 更多