Pandas: Create another column while splitting each row from the first column
<p>Goal create a second column from the first column</p>

<pre><code>column1, column2
Hello World, #HelloWord
US Election, #USElection
</code></pre>

<p>I have a simple file that has a one column</p>

<pre><code>columnOne
Hello World
US Election
Movie Night
</code></pre>

<p>I wrote following function</p>

<pre><code>&gt;&gt;&gt; def newColumn(row):
...     r = "#" + "".join(row.split(" "))
...     return r
</code></pre>

<p>then I did following to create the second column using pandas</p>

<pre><code>df['column2'] = df.apply (lambda row: newColumn(row),axis=1)
</code></pre>

<p>But I end up with following error: </p>

<pre><code>Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  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 "&lt;stdin&gt;", line 1, in &lt;lambda&gt;
  File "&lt;stdin&gt;", 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')
</code></pre>

<p>so I change the split to following: </p>

<pre><code>r = "".join(row.str.split(" "))
</code></pre>

<p>But that didn't help</p>

<p>Your general approach is totally fine, you just have a few problems. When you use apply on an entire dataframe, it will pass either a row or a column to the function it is applying. In your case, you don't want a row or a column - you want the string that is within each cell in the first column. So, instead of running <code>df.apply</code>, you want <code>df['columnOne'].apply</code>.</p>

<p>Here's what I would do: </p>

<pre><code>import pandas as pd

df = pd.DataFrame(['First test here', 'Second test'], columns=['A'])

# Note that this function expects a string, and returns a string
def new_string(s):
    # Get rid of the spaces
    s = s.replace(' ','')
    # Add the hash
    s = '#' + s
    return s

# The, apply it to the first column, and save it in the second, new column
df['B'] = df['A'].apply(new_string)
</code></pre>

<p>Or, if you really want it in a one-liner:</p>

<pre><code>df['B'] = df['A'].apply(lambda x: '#' + x.replace(' ',''))
</code></pre>

python pandas