将 pandas 数据框“对象”列转换为浮点数时出现问题

问题描述 投票:0回答:1

我正在尝试将 pandas 数据框中的 2 列转换为浮点值,因为它们当前被列为“对象”。当我尝试使用 .astype() 进行转换时,一列将被放置为值 0 而不是原始数字,第二列将转换为浮点数,但会删除小数点后的数字。我需要执行一些计算并需要浮点数数据。

我有包含 2 列的原始数据框:价格和数量

          price               qty
0    0.00080000   157523.03870305
1    0.00080300    75173.00864078
2    0.00080450    67683.65347307
3    0.00082162    14939.84800485
4    0.00082300    47508.48349310
5    0.00085000    20000.00000000

price    object
qty      object

当我尝试使用 .astype() 进行转换时,价格列返回 0 并且 qty 删除小数点:

     price     qty
0        0  157523
1        0   75173
2        0   67684
3        0   14940
4        0   47508
5        0   20000

price      float64
qty        float64

这是代码:

df['price'] = df['price'].astype(float)
bid['qty'] = bid['qty'].astype(float)
print(df)
print(df.dtypes)

预期输出:

          price               qty
0    0.00080000   157523.03870305
1    0.00080300    75173.00864078
2    0.00080450    67683.65347307
3    0.00082162    14939.84800485
4    0.00082300    47508.48349310
5    0.00085000    20000.00000000

price      float64
qty        float64
python pandas dataframe type-conversion
1个回答
0
投票

代码:

import pandas as pd

data = {
    'price': ['0.00080000', '0.00080300', '0.00080450', '0.00082162', '0.00082300', '0.00085000'],
    'qty': ['157523.03870305', '75173.00864078', '67683.65347307', '14939.84800485', '47508.48349310', '20000.00000000']
}

df = pd.DataFrame(data)

# Convert 'price' and 'qty' columns to float with correct formatting

df['price'] = pd.to_numeric(df['price'], errors='coerce')
df['qty'] = pd.to_numeric(df['qty'], errors='coerce')
df['price'] = df['price'].round(8)
df['qty'] = df['qty'].round(8)

# Print the DataFrame and its data types
print(df)
print(df.dtypes)

输出:

© www.soinside.com 2019 - 2024. All rights reserved.