您好,欢迎来到[编程问答]网站首页   源码下载   电子书籍   软件下载   专题
当前位置:首页 >> 编程问答 >> 其他语言 >> (python)pandas中如何将列中数据进行转换,如46k => 4600?

(python)pandas中如何将列中数据进行转换,如46k => 4600?

来源:网络整理     时间:2018/1/29 12:19:37     关键词:

关于网友提出的“ (python)pandas中如何将列中数据进行转换,如46k => 4600?”问题疑问,本网通过在网上对“ (python)pandas中如何将列中数据进行转换,如46k => 4600?”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:

问题: (python)pandas中如何将列中数据进行转换,如46k => 4600?
描述:

源数据原类型期望值
4.6kobject4600
2kobject2000
5.9kobject5900

尝试过使用一下方法

  1. pandas.apply()
def f(x):
    if('k' in str(x)):
        return float(x[:-1]) * 1000
    return x
df['views'] =df[['view']].apply(f)

错误提示

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in ()
      3         return float(x[:-1]) * 1000
      4     return x
----> 5 df['views'] =df[['view']].apply(f)

~/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)
   4260                         f, axis,
   4261                         reduce=reduce,
-> 4262                         ignore_failures=ignore_failures)
   4263             else:
   4264                 return self._apply_broadcast(f, axis)

~/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in _apply_standard(self, func, axis, ignore_failures, reduce)
   4356             try:
   4357                 for i, v in enumerate(series_gen):
-> 4358                     results[i] = func(v)
   4359                     keys.append(v.name)
   4360             except Exception as e:

 in f(x)
      1 def f(x):
      2     if('k' in str(x)):
----> 3         return float(x[:-1]) * 1000
      4     return x
      5 df['views'] =df[['view']].apply(f)

~/anaconda3/lib/python3.6/site-packages/pandas/core/series.py in wrapper(self)
     95             return converter(self.iloc[0])
     96         raise TypeError("cannot convert the series to "
---> 97                         "{0}".format(str(converter)))
     98 
     99     return wrapper

TypeError: ("cannot convert the series to ", 'occurred at index view')
  1. map()
def f(x):
    if('k' in str(x)):
        return int(x[:-1]) * 1000
    return x
df['views'] = map(f,df['view'])

结果:

求大神帮忙指定下


解决方案1:

map函数返回的是一个生成器,你要把这个生成器初始化后再赋值给df:

def f(x):
    if('k' in str(x)):
        return int(x[:-1]) * 1000
    return x
# 初始化为list再赋值
df['views'] = list(map(f,df['view']))

如果不行你再试试

df['views'] = np.array(list(map(f,df['view'])))

反正就是这个意思,你可以先在ipython中运行出来看看能不能赋值,再进程序跑
你也可以把数据发给我,我帮你写好,因为没具体的数据,我也不知道会出现啥情况2333333

apply函数我没用过,学习了,我研究下,我用pandas用的也不多
多嘴一句:别迭代DataFrame,一般比较慢,迭代numpy的ndarry会快很多,原来写程序发现的坑


以上介绍了“ (python)pandas中如何将列中数据进行转换,如46k => 4600?”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/4537266.html

相关图片

相关文章