[英]Automatic Data type conversion in pandas for each cell
我有这个 dataFrame
df = pd.DataFrame({"A":["1","2","aj"],"B":["1.5555","899999999999999999999999","dfhasdi"]})
这给出了 output
A B
0 1 1.5555
1 2 899999999999999999999999
2 aj dfhasdi
每个单元格的数据类型是
A B
0 <class 'str'> <class 'str'>
1 <class 'str'> <class 'str'>
2 <class 'str'> <class 'str'>
每个单元格所需的数据类型是
A B
0 <class 'int'> <class 'float'>
1 <class 'int'> <class 'int'>
2 <class 'str'> <class 'str'>
到目前为止我做到了
df = df.apply(pd.to_numeric, errors='ignore')
这不会改变数据类型。
如果需要区分同一列中的整数、浮点数和字符串,请使用DataFrame.applymap
使用双try-except
语句进行元素检查:
def f(x):
try:
return int(x)
except Exception:
try:
return float(x)
except Exception:
return x
df = df.applymap(f)
print (df)
A B
0 1 1.5555
1 2 899999999999999999999999
2 aj dfhasdi
print (df.applymap(type))
A B
0 <class 'int'> <class 'float'>
1 <class 'int'> <class 'int'>
2 <class 'str'> <class 'str'>
接近您的解决方案,但如果将字符串与整数混合在解决方案中得到浮点数:
df = df.apply(pd.to_numeric, errors='coerce').fillna(df)
print (df)
A B
0 1.0 1.5555
1 2.0 899999999999999958056960.0
2 aj dfhasdi
print (df.applymap(type))
A B
0 <class 'float'> <class 'float'>
1 <class 'float'> <class 'float'>
2 <class 'str'> <class 'str'>
如果相同类型(字符串 repr),它会更好地工作:
df = df.apply(pd.to_numeric, errors='coerce').fillna(df)
print (df)
A B
0 1 1.5555
1 2 899999999999999958056960.0
2 4 dfhasdi
print (df.applymap(type))
A B
0 <class 'int'> <class 'float'>
1 <class 'int'> <class 'float'>
2 <class 'int'> <class 'str'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.