代码之家  ›  专栏  ›  技术社区  ›  user48956

将列类型编辑为固定宽度字符串(在现有数据帧内)

  •  1
  • user48956  · 技术社区  · 6 年前

    我在一个数据帧中有一列字符串对象。

    有很多答案( How to set dtypes by column in pandas DataFrame

    import pandas as pd
    import numpy as np
    
    df = pd.Series(["1", "22", "333", "4444", "55555"], name="c").to_frame()
    df["c"] = df["c"].astype("int")
    list(df.dtypes)  # [dtype('int64')]
    

    ... 但对于固定宽度的字符串,这是失败的:

    df = pd.Series(["1", "22", "333", "4444", "55555"], name="c").to_frame()
    df["c"] = df["c"].astype("|S2")
    print list(df.dtypes)  # [dtype('O')]
    

    内容 df["c"]

    print np.array(["1", "22", "333", "4444", "55555"]).astype("|S2")
    
    ['1' '22' '33' '44' '55']
    

    所以。。如何更改数据帧列的数据类型(不分配一个全新的数据帧——只想更改那一列)

    1 回复  |  直到 6 年前
        1
  •  0
  •   Andy Hayden    6 年前

    pop 重新分配前的列:

    In [11]: df.dtypes
    Out[11]:
    c    object
    dtype: object
    
    In [12]: df['c'] = df.pop('c').astype('|S2')
    
    In [13]: df.dtypes
    Out[13]:
    c    |S2
    dtype: object