如何在熊猫python列中仅将科学值转换为int

时间:2019-10-23 07:16:10

标签: python pandas

我有一个df,

     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

代码列包含所有类型的值。我想在代码变量中将科学计数法转换为int。我试图将该列转换为int,但由于它具有112AV67TYG,因此无法解析字符串。请帮助。

预期输出:

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

2 个答案:

答案 0 :(得分:0)

尝试一下:

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

答案 1 :(得分:0)

condition = df.Code.str.contains('E+', regex=False)
df.loc[condition, 'Code'] = df.loc[condition, 'Code'].astype(int)