Limit number of characters per Dataframe Python column

Asked

Viewed 392 times

0

Need to limit the number of characters per column in 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 Dataframe’s input in the SQL table with the following parameters:

Column J up to 10 characters. Column K up to 14 characters. Column L 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 someone help me?

1 answer

0

Solution found:

data['J'] = data['J'].str[:10]
data['K'] = data['K'].str[:14]
data['L'] = data['L'].str[:1]

data

Browser other questions tagged

You are not signed in. Login or sign up in order to post.