【问题标题】:Converting a column of strings to numbers in Pandas在 Pandas 中将一列字符串转换为数字
【发布时间】:2013-11-04 22:07:50
【问题描述】:

如何将 Units 列变为数字?

我有一个谷歌电子表格,我正在阅读日期列中的转换很好.. 但我没有太多运气让单位销售列转换为数字我包括所有使用请求获取的代码数据:

from StringIO import StringIO 
import requests
#act = requests.get('https://docs.google.com/spreadsheet/ccc?key=0Ak_wF7ZGeMmHdFZtQjI1a1hhUWR2UExCa2E4MFhiWWc&output=csv&gid=1')
dataact = act.content
actdf = pd.read_csv(StringIO(dataact),index_col=0,parse_dates=['date'])
actdf.rename(columns={'Unit Sales': 'Units'}, inplace=True) #incase the space in the name is messing me up

我尝试将 Units 转换为 numeric 的不同方法

actdf=actdf['Units'].convert_objects(convert_numeric=True)
#actdf=actdf['Units'].astype('float32')

然后我想重新采样,我得到奇怪的字符串连接,因为数字仍然是字符串

#actdfq=actdf.resample('Q',sum)
#actdfq.head()
actdf.head()
#actdf

所以 df 看起来像这样,只有单位和日期索引

date
2013-09-01    3,533
2013-08-01    4,226
2013-07-01    4,281
Name: Units, Length: 161, dtype: object

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你必须指定千位分隔符:

    actdf = pd.read_csv(StringIO(dataact), index_col=0, parse_dates=['date'], thousands=',')
    

    【讨论】:

      【解决方案2】:
      This will work
      
      In [13]: s
      Out[13]: 
      0    4,223
      1    3,123
      dtype: object
      
      In [14]: s.str.replace(',','').convert_objects(convert_numeric=True)
      Out[14]: 
      0    4223
      1    3123
      dtype: int64
      

      【讨论】:

        猜你喜欢
        • 2019-04-08
        • 1970-01-01
        • 2016-08-30
        • 2020-10-22
        • 2018-01-27
        • 1970-01-01
        • 2020-04-08
        • 2019-01-14
        • 2016-09-17
        相关资源
        最近更新 更多