我的代码在下面
将pd.to_numeric应用于应该为int或float但作为对象出现的列。我们可以像应用np.where
一样将更多内容转换为熊猫吗?if df.dtypes.all() == 'object':
df=df.apply(pd.to_numeric,errors='coerce').fillna(df)
else:
df = df
答案 0 :(得分:2)
一个简单的衬里是{
"message": "candidate job listing",
"status": true,
"data": [
{
"id": 1,
"company_name_shown_job": "xyz company",
"job_title": "Android Developer",
"job_description": null,
"experience_tags": [
{
"id": 2,
"employer_job_post_id": 1,
"experience_in": "Android"
},
{
"id": 3,
"employer_job_post_id": 1,
"experience_in": "Php"
}
]
},
{
"id": 2,
"company_name_shown_job": "Abc company",
"job_title": "Web Developer",
"job_description": "<p>Lorem ipsum dolor sit amet,laborum.</p>",
"experience_tags": [
{
"id": 4,
"employer_job_post_id": 2,
"experience_in": "Swift"
},
{
"id": 5,
"employer_job_post_id": 2,
"experience_in": "Java"
}
]
}
]
和assign
,它将重新分配现有的列
selest_dtypes
df.assign(**df.select_dtypes('O').apply(pd.to_numeric,errors='coerce').fillna(df))
:
np.where
示例(选中df[:] = (np.where(df.dtypes=='object',
df.apply(pd.to_numeric,errors='coerce').fillna(df),df)
列):
Price
d = {'CusID': {0: 1, 1: 2, 2: 3},
'Name': {0: 'Paul', 1: 'Mark', 2: 'Bill'},
'Shop': {0: 'Pascal', 1: 'Casio', 2: 'Nike'},
'Price': {0: '24000', 1: 'a', 2: '900'}}
df = pd.DataFrame(d)
print(df)
CusID Name Shop Price
0 1 Paul Pascal 24000
1 2 Mark Casio a
2 3 Bill Nike 900
df.to_dict()
{'CusID': {0: 1, 1: 2, 2: 3},
'Name': {0: 'Paul', 1: 'Mark', 2: 'Bill'},
'Shop': {0: 'Pascal', 1: 'Casio', 2: 'Nike'},
'Price': {0: '24000', 1: 'a', 2: '900'}}
答案 1 :(得分:2)
您的if / else等效值为df.mask
df_out = df.mask(df.dtypes =='O', df.apply(pd.to_numeric, errors='coerce')
.fillna(df))