Limit amount of characters per Python DataFrame column
I need to limit the amount of characters per column in the Dataframe to insert in SQL Server.
Example:
I have a DataFrame with 3 columns and 1k of rows (column J/ K/ L) and I need to limit the insert of this DataFrame in the SQL table with the following parameters:
Column J with up to 10 characters. Column K with up to 14 characters. Column L with up to 1 characters.
import pandas as pd
import numpy as np
def c10(str):
maxx = 10
if len(str) > maxx:
return str[:maxx]
else:
return str
def c14(str):
maxx = 14
if len(str) > maxx:
return str[:maxx]
else:
return str
def c1(str):
maxx = 1
if len(str) > maxx:
return str[:maxx]
else:
return str
dic = { 'J' : ['JOE','JULIA','INFORMAÇÃO QUALQUER'],
'K' : ['OUTRA COISA','KACCE','MAIS OUTRA SITUAÇÃO'],
'L' : ['LEO','LUKE','LEVI'],
'M' : ['MORGAN','MARIE',np.nan] }
data = pd.DataFrame(dic)
data
data['J'] = c10(data['J'])
data['K'] = c14(data['K'])
data['L'] = c1(data['L'])
data
Can anyone help me?
0
Author: DAYMON CARVALHO REBAC, 2020-01-09
1 answers
Solution found:
data['J'] = data['J'].str[:10]
data['K'] = data['K'].str[:14]
data['L'] = data['L'].str[:1]
data
0
Author: DAYMON CARVALHO REBAC, 2020-01-09 18:10:31