Home > Back-end >  How to apply text_wrapper on dataframe column
How to apply text_wrapper on dataframe column

Time:10-12

I have dataframe

In [1]: import pandas as pd
In [2]: data = {'A': [" tell me more about your issue please", "OKEY WILL DO", "IT DOESNT WORK HELP ME PLEASE"], 'B': [4, 5, 6], 'C': [7, 8, 9]}
In [3]: df = pd.DataFrame(data)
In [4]: df

And I want to apply to get in new column split text with max 8 characters

import textwrap
lines = textwrap.wrap(text, 8, break_long_words=False)

I tried something like

df['Split'] = df['A'].map(textwrap.wrap(df['A'],8, break_long_words = False))
 and .apply

Not only I think it is totally nonsense what I have in code, it also returns error

AttributeError: 'Series' object has no attribute 'expandtabs'

But I am total dumbass and I dont know how to get it running. Please could you help me?

Thanks!

CodePudding user response:

Use lambda function:

df['Split'] = df['A'].map(lambda x: textwrap.wrap(x,8, break_long_words = False))

Or:

df['Split'] = df['A'].apply(lambda x: textwrap.wrap(x,8, break_long_words = False))
  • Related