Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the number of strings (characters/words) in a column using DataFrame

Trying to limit the number of character shown in the output of a DataFrame.

Here is an example of a DataFrame:

     Abc                       XYZ
0  Hello   How are you doing today
1   Good   This is a job well done
2    Bye          See you tomorrow
3  Books  Read chapter 1 to 5 only

Desired output:

     Abc                       XYZ
0  Hello                   How are 
1   Good                   This is
2    Bye                   See you
3  Books              Read chapter

This is what I tried:

pd.set_option('display.max_info_rows', 2)
pd.set_option('display.max_info_columns', 2)
pd.set_option('display.max_colwidth', 2)

max_info_rows and max_info_columns did not do anything, while max_colwidth actually expanded the characters further.

Anyway to limit the number of characters in a dataframe?

Thanks!

like image 701
Mick Avatar asked Feb 03 '26 12:02

Mick


1 Answers

Try this:

df.XYZ.apply(lambda x : x.rsplit(maxsplit=len(x.split())-2)[0])

0         How are
1         This is
2         See you
3    Read chapter

just reassign it back:

df.XYZ = df.XYZ.apply(lambda x : x.rsplit(maxsplit=len(x.split())-2)[0])
print(df)

     Abc           XYZ
0  Hello       How are
1   Good       This is
2    Bye       See you
3  Books  Read chapter
like image 185
anky Avatar answered Feb 06 '26 00:02

anky