我有一个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

最佳答案

尝试这个:

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

关于python - 如何在 Pandas python列中仅将科学值转换为int,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58517406/

10-09 21:47