目标从第一列创建第二列
column1, column2
Hello World, #HelloWord
US Election, #USElection
columnOne
Hello World
US Election
Movie Night
我写了以下功能
>>> def newColumn(row):
... r = "#" + "".join(row.split(" "))
... return r
然后我做了以下使用pandas创建第二列
df['column2'] = df.apply (lambda row: newColumn(row),axis=1)
但我最终得到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 3972, in apply
return self._apply_standard(f, axis, reduce=reduce)
File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 4064, in _apply_standard
results[i] = func(v)
File "<stdin>", line 1, in <lambda>
File "<stdin>", line 2, in newColumn
File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/generic.py", line 2360, in __getattr__
(type(self).__name__, name))
AttributeError: ("'Series' object has no attribute 'split'", u'occurred at index 0')
所以我将拆分更改为以下内容:
r = "".join(row.str.split(" "))
但这没有帮助
解决方法:
尝试列表comprehesion:
df = pandas.DataFrame({'columnOne': ['Hello World', 'US Election', 'Movie Night']})
df['column2'] = ['#' + item.replace(' ', '') for item in df.columnOne]
In [2]: df
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。