[英]distinguish decimal and string columns in a pandas dataframe
I need to identify which columns in a dataframe are decimals and which are strings.我需要确定 dataframe 中的哪些列是小数,哪些是字符串。
Using df.dtypes gives 'object' for both column types:使用 df.dtypes 为两种列类型提供“对象”:
import pandas as pd
import decimal
data = {'dec1': [1.1, 1.2],'str1': ["a","b"]}
df = pd.DataFrame(data)
df.dec1 = df.dec1.apply(lambda x: decimal.Decimal(x))
df.dtypes
I am using the following code to know which are decimals, but there has to be a more pythonic way for something so basic.我正在使用下面的代码来知道哪些是小数,但是对于如此基本的东西,必须有一种更 Pythonic 的方式。 What is it?
它是什么?
actual_col_types = df.iloc[0].apply(type)
df_decimals = df.loc[:,actual_col_types==decimal.Decimal]
Use isinstance
, what should be more preferable like type, link :使用
isinstance
,应该更喜欢 type , link :
mask = df.iloc[0].map(lambda x: isinstance(x, decimal.Decimal))
df_decimals = df.loc[:,mask]
print (df_decimals)
dec1
0 1.10000000000000008881784197001252323389053344...
1 1.19999999999999995559107901499373838305473327...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.