我用以下代码创建了一个名为df的熊猫数据中心:
import numpy as np
import pandas as pd
ds = {'col1' : ["1","2","3","A"], "col2": [45,6,7,87], "col3" : ["23","4","5","6"]}
df = pd.DataFrame(ds)dataframe如下所示:
print(df)
col1 col2 col3
0 1 45 23
1 2 6 4
2 3 7 5
3 A 87 6现在,col1和col3是对象:
print(df.info())
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 col1 4 non-null object
1 col2 4 non-null int64
2 col3 4 non-null object我想在可能的情况下将对象列转换为浮动。
例如,我可以将col3转换为如下所示的浮动:
df['col3'] = df['col3'].astype(float)但我不能将col1转换为浮点数:
df['col1'] = df['col1'].astype(float)
ValueError: could not convert string to float: 'A'是否有可能创建一个代码,在可能的情况下将对象列转换为浮点数,并传递不可能的情况(因此,不抛出停止进程的错误)?我想这跟例外有关吧?
发布于 2022-07-12 09:56:08
我认为您可以测试字符串中的内容是否为对象,在这种情况下将不会进行转换。你试过这个吗?
for y in df.columns:
if(df[y].dtype == object):
continue
else:
# your treatement here或者,显然在pandas 0.20.2中,有一个函数可以进行测试:is_string_dtype(df['col1'])
在列的所有值都是相同类型的情况下,如果值是混合的,则在df.values上迭代。
发布于 2022-07-12 09:54:39
我已经安排好了。
def convert_float(x):
try:
return x.astype(float)
except:
return x
cols = df.columns
for i in range(len(cols)):
df[cols[i]] = convert_float(df[cols[i]])
print(df)
print(df.info())https://stackoverflow.com/questions/72950184
复制相似问题