Function to create Column

1

Hello,

I'm trying to create a column using a function, but it's giving an error, which should be silly to fix, and even then I could not, come on:

import pandas as pd
import numpy as np 
import matplotlib.pyplot as plt

df = pd.read_csv("Planilha_Final.csv")

# Criando Coluna com o Nome da Regua, Prazo e se tem ou não Crédito
df = df[df['Segmento'].str.contains('|')]
def cria_acao(string_nome):
    try:
        return string_nome.split("|")[0]
    except:
        return ''

def cria_prazo(string_nome):
    try:
        return string_nome.split("|")[1]
    except:
        return ''

def cria_credito(string_nome):
    try:
        return string_nome.split("|")[2]
    except:
        return ''

df['Régua'] = df['Segmento'].apply(cria_acao)
df['Prazo'] = df['Segmento'].apply(cria_prazo)
df['Crédito'] = df['Segmento'].apply(cria_credito)

This function above worked, created the term columns and everything, the problem is in the next, I tried to create a function so that when the value of the Term Column is equal to 5 days, it creates a discount column with the information of 10%, I tried:

def cria_colunas(string_campanha):
    if df[string_campanha].str.contains(' 5 dias ') == True:
        return '10%'
    else:
        return ''
df['Desconto'] = df['Envios'].apply(cria_colunas)

And the error that appears is as follows:

KeyError: ' 5 dias '

The space between the "in 5 days" is on purpose, the column is like this, something that I will try to solve in the next one, but I wanted to know what I'm missing in the function.

If anyone can help, I'm very grateful!

Hugs,

    
asked by anonymous 22.08.2018 / 16:02

1 answer

1

Its cria_colunas pends function receives string . Making df[string_campanha] causes a column to be found in df with the name string_campanha . Because this column does not exist, it generates the error KeyError: ' 5 dias ' . What you want to do is check if there is a string in the 'Submissions' column and generate a 'Discount' column from that. When we do

df['Desconto'] = df['Envios'].apply(cria_colunas)

We are applying the create_columns function for each row in the 'Shipping' column and placing the response on the row of the 'Discount' column you created now.

The correct function would be:

def cria_colunas(linha_envios):
    if ' 5 dias ' in linha_envios:
        return '10%'
    else:
        return ''
    
22.08.2018 / 16:18