将pandas中的Decimal列转换为float列

时间:2019-08-11 13:45:08

标签: python pandas

我有以下数据框:

import iconv from 'iconv-lite';
import { Buffer } from 'buffer';

function fetchXML() {
  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest();

    request.onload = () => {
      if (request.status === 200) {
        resolve(iconv.decode(Buffer.from(request.response), 'iso-8859-1'));
      } else {
        reject(new Error(request.statusText));
      }
    };
    request.onerror = () => reject(new Error(request.statusText));
    request.responseType = 'arraybuffer';

    request.open('GET', 'http://www.band.uol.com.br/rss/colunista_64.xml');
    request.setRequestHeader('Content-type', 'text/xml; charset=ISO-8859-1');
    request.send();
  });
}

fetchXML().then(response => 
    console.log(response)
);

如果要创建另外一个名为“ price_float”的列,该列与“ price”相同,但带有浮点数(稍后使用不支持Decimal的matplotlib进行绘制)。

我尝试过:

buffer

但是我得到了

stream

2 个答案:

答案 0 :(得分:1)

只需模拟您的示例DataFrame:

示例数据帧:

>>> df2
    price  tpo  tpo_count
0  1.4334    A          1
1  1.4335   BC          2
2  1.4336  BCD          3
3  1.4337    D          1
>>> print(df2.dtypes)
price        object
tpo          object
tpo_count     int64
dtype: object

解决方案..

>>> df2['price_float'] = df2['price'].astype(float)
>>> df2
    price  tpo  tpo_count  price_float
0  1.4334    A          1       1.4334
1  1.4335   BC          2       1.4335
2  1.4336  BCD          3       1.4336
3  1.4337    D          1       1.4337

现在您已经创建了新的float列。.

>>> print(df2.dtypes)
price           object
tpo             object
tpo_count        int64
price_float    float64
dtype: object

答案 1 :(得分:0)

您可以使用astype函数:

color = Sex