Python 如何仅将列中的科学值转换为int
我有一个dfPython 如何仅将列中的科学值转换为int,python,pandas,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 t
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
试试这个:
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