我四处走动,尝试了很多不同的方式,所以我猜我的核心理解是错误的.我将非常感谢帮助理解我的编码/解码问题.
我从SQL导入数据帧,似乎有些数据类型:float64被转换为Object.因此,我无法做任何计算.我无法将Object转换回float64.
df.head()
Date WD Manpower 2nd CTR 2ndU T1 ??T2 ??T3 ??T4
2013/4/6 6 NaN 2,645 5.27% 0.29 407 533 454 368
2013/4/7 7 NaN 2,118 5.89% 0.31 257 659 583 369
2013/4/13 6 NaN 2,470 5.38% 0.29 354 531 473 ??383
2013/4/14 7 NaN 2,033 6.77% 0.37 396 748 681 458
2013/4/20 6 NaN 2,690 5.38% 0.29 361 528 541 381
Run Code Online (Sandbox Code Playgroud)
df.dtypes
WD float64
Manpower float64
2nd object
CTR object
2ndU float64
T1 object
T2 object
T3 object
T4 object
T5 object
dtype: object
Run Code Online (Sandbox Code Playgroud)
SQL表:

EdC*_*ica 24
您只需调用convert_objects以下内容即可转换大多数列:
In [36]:
df = df.convert_objects(convert_numeric=True)
df.dtypes
Out[36]:
Date object
WD int64
Manpower float64
2nd object
CTR object
2ndU float64
T1 int64
T2 int64
T3 int64
T4 float64
dtype: object
Run Code Online (Sandbox Code Playgroud)
对于列'2nd'和'CTR',我们可以调用矢量化str方法来替换千位分隔符并删除'%'符号,然后astype转换:
In [39]:
df['2nd'] = df['2nd'].str.replace(',','').astype(int)
df['CTR'] = df['CTR'].str.replace('%','').astype(np.float64)
df.dtypes
Out[39]:
Date object
WD int64
Manpower float64
2nd int32
CTR float64
2ndU float64
T1 int64
T2 int64
T3 int64
T4 object
dtype: object
In [40]:
df.head()
Out[40]:
Date WD Manpower 2nd CTR 2ndU T1 ??T2 T3 T4
0 2013/4/6 6 NaN 2645 5.27 0.29 407 533 454 368
1 2013/4/7 7 NaN 2118 5.89 0.31 257 659 583 369
2 2013/4/13 6 NaN 2470 5.38 0.29 354 531 473 ??383
3 2013/4/14 7 NaN 2033 6.77 0.37 396 748 681 458
4 2013/4/20 6 NaN 2690 5.38 0.29 361 528 541 381
Run Code Online (Sandbox Code Playgroud)
或者您可以在没有调用的情况下执行上面的字符串处理操作astype,然后调用一次convert_objects转换所有内容.
UPDATE
由于版本0.17.0 convert_objects已弃用且没有顶级功能,因此您需要执行以下操作:
df.apply(lambda col:pd.to_numeric(col, errors='coerce'))
请参阅文档和此相关问题:pandas:to_numeric用于多列
不推荐使用convert_objects。
对于大于等于 0.17.0的熊猫,请使用pd.to_numeric
df["2nd"] = pd.to_numeric(df["2nd"])
Run Code Online (Sandbox Code Playgroud)
我df在从具有多个内部标题行的 Excel 工作表创建的 DataFrame ( ) 中遇到了这个问题。
从 中清除内部标题行后df,列的值属于“非空对象”类型 ( DataFrame.info())。
此代码将多列的所有数值一次性转换为 int64 和 float64:
for i in range(0, len(df.columns)):
df.iloc[:,i] = pd.to_numeric(df.iloc[:,i], errors='ignore')
# errors='ignore' lets strings remain as 'non-null objects'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59179 次 |
| 最近记录: |