首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在pandas python列中仅将科学值转换为int

如何在pandas python列中仅将科学值转换为int
EN

Stack Overflow用户
提问于 2019-10-23 15:16:10
回答 2查看 33关注 0票数 1

我有一个df,

代码语言:javascript
复制
     ID  Code        Desc
     1   146         ReadWriteThink offers hundreds of classroom  
     2   112AV67TYG  language arts and literacy
     3   3.75E+11    View the artwork for a U.S
     4   3.22E+11    short passage on the details of this eloquent folktale

code列包含所有类型的值。我想在code变量中将科学记数法转换为int。我试图将该列转换为int,但由于它有112AV67TYG,它显示无法解析字符串。请帮帮忙。

预期输出:

代码语言:javascript
复制
ID  Code                  Desc
     1   146              ReadWriteThink offers hundreds of classroom  
     2   112AV67TYG       language arts and literacy
     3   375072000000     View the artwork for a U.S
     4   321881000000     short passage on the details of this eloquent 
                          folktale
EN

回答 2

Stack Overflow用户

发布于 2019-10-23 15:33:31

试试这个:

代码语言:javascript
复制
df = pd.DataFrame({"code" : ['146','112AV67TYG','3.75E+11','3.22E+11']})
import ast
def try_convert(x):
    try:
        return int(ast.literal_eval(x))
    except:
        return x
df['new_code'] = df['code'].apply(lambda x : try_convert(x))
df
#######
    code        new_code
0   146         146
1   112AV67TYG  112AV67TYG
2   3.75E+11    375000000000
3   3.22E+11    322000000000
票数 0
EN

Stack Overflow用户

发布于 2019-10-23 15:42:51

代码语言:javascript
复制
condition = df.Code.str.contains('E+', regex=False)
df.loc[condition, 'Code'] = df.loc[condition, 'Code'].astype(int)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58517406

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档