【问题标题】:Pandas convert float in scientific notation to stringPandas 将科学计数法中的浮点数转换为字符串
【发布时间】:2016-12-15 06:44:00
【问题描述】:

我使用read_csv() 加载了一个看起来像这样的数据集

userid
NaN
1.091178e+11
1.137856e+11

我想将用户 ID 转换为字符串。一种解决方案是将keep_default_na=False 添加到read_csv(),此SO 建议:Converting long integers to strings in pandas (to avoid scientific notation)

假设我不想使用keep_default_na=False。有没有办法将用户id列转换为str。

我尝试了df.userid.astype(str) 并得到了1.091178e+11 的回复。我期待的是扩展形式而不是科学形式的结果。

我该怎么办?

【问题讨论】:

  • 是否可以使用参数dtype={'userid':str} 并且对您有用?
  • 您可以应用字符串格式df.userid.apply(lambda x: '{:.0f}'.format(x))

标签: python pandas


【解决方案1】:

您可以使用mapapply,如comment 中所述:

print (df.userid.map(lambda x: '{:.0f}'.format(x)))
0             nan
1    109117800000
2    113785600000
Name: userid, dtype: object

df.userid = df.userid.map(lambda x: '{:.0f}'.format(x))
print (df)
         userid
0           nan
1  109117800000
2  113785600000

我想知道map是否会更快,但它是一样的:

#[300000 rows x 1 columns]
df = pd.concat([df]*100000).reset_index(drop=True)
#print (df)

In [40]: %timeit (df.userid.map(lambda x: '{:.0f}'.format(x)))
1 loop, best of 3: 211 ms per loop

In [41]: %timeit (df.userid.apply(lambda x: '{:.0f}'.format(x)))
1 loop, best of 3: 210 ms per loop

另一种解决方案是to_string,但是很慢:

print(df.userid.to_string(float_format='{:.0f}'.format))
0            nan
1   109117800000
2   113785600000

In [41]: (df.userid.to_string(float_format='{:.0f}'.format))
1 loop, best of 3: 2.52 s per loop

【讨论】:

    【解决方案2】:

    我在使用read_json 方法从json 文件读取数据帧后偶然发现了这个问题,不幸的是它没有keep_default_na 参数。

    解决方案是将长浮点数转换为np.int64,然后再将它们转换为str

    In [53]: tweet_id_sample = tweets.iloc[0]['id']
             tweet_id_sample
    Out[53]: 8.924206435553362e+17
    
    In [54]: tweet_id_sample.astype(str)
    Out[54]: '8.924206435553362e+17'
    
    In [55]: tweet_id_sample.astype(np.int64).astype(str)
    Out[55]: '892420643555336192'
    
    In [56]: # This overflows
             tweet_id_sample.astype(int)
    Out[56]: -2147483648
    

    【讨论】:

      猜你喜欢
      • 2014-07-01
      • 2020-06-10
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多