Reputation: 147
I am working various columns in a csv file with pandas and jupyter notebook I would need to truncate a string that is too long in a column eg:
test_column
abcde 1234 free foo row saw hello number ok by test
free foo row saw 1234 hello test
.....
I would like the rest to be truncated in the column after 15 characters:
test_column
abcde 1234 free //---->after 15 charter
free foo row sa //---->after 15 charter
..... i'm trying with
df = df[df['test_column'].map(lambda x: len(str(x)) < 15)]
df
but unfortunately I delete the whole rows longer than 15 instead of truncating it! how could i solve it ?
thanks ?
Upvotes: 2
Views: 1912
Reputation: 61910
Just do:
res = df["test_column"].str[:15]
print(res)
Output
0 abcde 1234 free
1 free foo row sa
Name: test_column, dtype: object
As an alternative use str.slice
:
res = df["test_column"].str.slice(stop=15)
Output
0 abcde 1234 free
1 free foo row sa
Name: test_column, dtype: object
Upvotes: 2