简体   繁体   中英

cannot change datatype from “from_dict” of dataframe

After df['a'].astype(float) from from_dict cannot be sum the column.
I expected the sum(a) should be 15 not 159 and I just want to show 15 only not whole dataframe table

code

x = [{'a': '1','b1': '2','b2': '3', 'c': '4'},{'a': '5','b1': '6','b2': '7','c': '8'},{'a': '9','b1': '10','b2': '11','c': '12'}]
import pandas as pd
df = pd.DataFrame.from_dict(x)

df['a'] = df['a'].astype(float)
df['total'] = df['a'].sum()
df

code output:

    a   b1  b2  c   total
0   1.0 2   3   4   15.0
1   5.0 6   7   8   15.0
2   9.0 10  11  12  15.0

Data type

df['a'].astype(float)
df.dtypes

a        float64
b1       object
b2       object
c        object
total    object
dtype: object

Expected Result

15

a转换为float您应该像这样保存它:

df['a']=df['a'].astype(float)

使用 df['a']=pd.to_numeric(df['a'],errors='coerce') 来改变类型

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM