【问题标题】:Python Pandas: Change type from float to float64 in a column which contains both numerical and string elementsPython Pandas:在包含数字和字符串元素的列中将类型从 float 更改为 float64
【发布时间】:2021-03-14 08:33:21
【问题描述】:

让我们假设以下pandas 数据框:

df = 
       Column1       Column2       Column3     Column4
       2007-01-02    1M            String1     String2 
       2007-01-02    1M            0.051695    0.0057984
       2007-01-02    1M            0.0498056   0.00725827
       2007-01-02    1M            0.0493161   0.00780772
       2007-01-02    1M            0.0492764   0.00810296
       2007-01-02    1M            0.0493988   0.00820139
       2007-01-02    1M            0.0495177   0.00829837
       2007-01-03    1M            String1     String2 
       2007-01-03    1M            0.0516506  0.00589057
       2007-01-03    1M            0.0496136  0.00726748
       2007-01-03    1M            0.0490747  0.00781708
       2007-01-03    1M            0.0490845   0.0081065
       2007-01-03    1M            0.0492069  0.00820219
       2007-01-04    1M            String1    String2     
       2007-01-04    1M            0.0510632  0.00589493
              ...    ...           ...        ...

Column3Column4 列被视为对象。当我检查Column3(即0.051695)的第二个元素的type 时,我得到float。我的问题是我是否可以将Column3Column4 的数字元素从float 更改为float64。我尝试了以下方法,但没有成功:

df[["Column3"]][df["Column3"]!="String1"] = 
df[["Column3"]][df["Column3"]!="String1"].astype(np.float64) 

这给了我错误

SettingWithCopyWarning: 试图在 DataFrame 中的切片副本上设置一个值。 尝试改用 .loc[row_indexer,col_indexer] = value

df.loc[:,"Column3"][df["Column3"]!="String1"] = 
df.loc[:,"Column3"][df["Column3"]!="String1"].astype(np.float64) 

这给了我错误

SettingWithCopyWarning: 正在尝试在 DataFrame 中的切片副本上设置值

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您的解决方案可以通过将掩码更改为loc 函数:

    mask = df["Column3"]!="String1"
    df.loc[mask,"Column3"] = df.loc[mask,"Column3"].astype(np.float64)
    

    另一个想法如果转换所有可能的数字,非数字生成缺失值,因此替换为原始值:

    df['Column3'] = pd.to_numeric(df['Column3'], errors='coerce').fillna(df['Column3'])
    

    为了测试可以使用检查type:

    print (df['Column3'].apply(type))
    0       <class 'str'>
    1     <class 'float'>
    2     <class 'float'>
    3     <class 'float'>
    4     <class 'float'>
    5     <class 'float'>
    6     <class 'float'>
    7       <class 'str'>
    8     <class 'float'>
    9     <class 'float'>
    10    <class 'float'>
    11    <class 'float'>
    12    <class 'float'>
    13      <class 'str'>
    14    <class 'float'>
    Name: Column3, dtype: object
    

    在我看来,最好还是只有数字列,但不匹配值的缺失值:

    df['Column3'] = pd.to_numeric(df['Column3'], errors='coerce')
    

    【讨论】:

    • 掩码解决方案在我的示例中似乎不起作用,但第三个建议似乎是一种选择。谢谢。
    猜你喜欢
    • 2016-05-23
    • 1970-01-01
    • 2021-11-02
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多