熊猫:合并两个数据框后如何防止科学计数法?

时间:2018-07-18 12:24:14

标签: python pandas dataframe

我想合并两个数据框,但是,一列包含nan,合并后,整数类型值用科学记数法记录。实际上,我只想获取其原始值。 输入:

import pandas as pd 
import numpy as np 
left=pd.DataFrame({'key':['one','two','three'],'other':[1,2,3]})

right=pd.DataFrame({'id':[600608457536718400,np.nan,96436390593326400],'key':['one','two','three']})

total=pd.merge(left,right,on=['key'],how='left')
print(left)
print(right)
print(total)

输出:

     key  other
0    one      1
1    two      2
2  three      3
             id    key
0  6.006085e+17    one
1           NaN    two
2  9.643639e+16  three
     key  other            id
0    one      1  6.006085e+17
1    two      2           NaN
2  three      3  9.643639e+16

预期:

     key  other            id
0    one      1  600608457536718400
1    two      2           NaN
2  three      3  96436390593326400

我尝试填充列id,然后转换列的类型,但是失败。

我尝试的方法:

right['id'].fillna(-1,inplace=True)
right['id']=right['id'].astype('int64')
total=pd.merge(left,right,on=['key'],how='left')

输出:

     key  other                  id
0    one      1  600608457536718336
1    two      2                  -1
2  three      3   96436390593326400

希望获得帮助!谢谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试使用这个吗?也许可能有效。基本上,在创建数据框时,我将类型更改为str。

import pandas as pd 
import numpy as np 
left=pd.DataFrame({'key':['one','two','three'],'other':[1,2,3]})

right=pd.DataFrame({'id':[str(600608457536718400),np.nan,str(96436390593326400)],'key':['one','two','three']})

total=pd.merge(left,right,on=['key'],how='left')
print(total)

这给出了以下输出

     key  other                  id
0    one      1  600608457536718400
1    two      2                 NaN
2  three      3   96436390593326400