How to add a specific number of characters to the end of string in Pandas?
<p>I am using the Pandas library within Python and I am trying to increase the length of a column with text in it to all be the same length. I am trying to do this by adding a specific character (this will be white space normally, in this example I will use "_") a number of times until it reaches the maximum length of that column. </p>

<p>For example:</p>

<p><strong>Col1_Before</strong></p>

<pre><code>A
B
A1R
B2
AABB4
</code></pre>

<p><strong>Col1_After</strong></p>

<pre><code>A____
B____
A1R__
B2___
AABB4
</code></pre>

<p>So far I have got this far (using the above table as the example). It is the next part (and the part that does it that I am stuck on).</p>

<pre><code>df['Col1_Max'] = df.Col1.map(lambda x: len(x)).max()
df['Col1_Len'] = df.Col1.map(lambda x: len(x))
df['Difference_Len'] = df ['Col1_Max'] - df ['Col1_Len']
</code></pre>

<p>I may have not explained myself well as I am still learning. If this is confusing let me know and I will clarify. </p>

<p>It isn't the most pandas-like solution, but you can try the following:</p>

<pre><code>col = np.array(["A", "B", "A1R", "B2", "AABB4"])
data = pd.DataFrame(col, columns=["Before"])
</code></pre>

<p>Now compute the maximum length, the list of individual lengths, and the differences:</p>

<pre><code>max_ = data.Before.map(lambda x: len(x)).max()
lengths_ = data.Before.map(lambda x: len(x))
diffs_ = max_ - lengths_
</code></pre>

<p>Create a new column called <code>After</code> adding the underscores, or any other character:</p>

<pre><code>data["After"] = data["Before"] + ["_"*i for i in diffs_]
</code></pre>

<p>All this gives:</p>

<pre><code>  Before  After
0      A  A____
1      B  B____
2    A1R  A1R__
3  AABB4  AABB4
</code></pre>

python pandas dataframe string-length maxlength