How to round value created on pandas?

Asked

Viewed 2,411 times

1

Hello Please, in pandas Python 3 I am creating this dataframe with the sum of another dataset:

total = cand_doacoes.groupby(['CPF_candidato', 'Nome_candidato', 'Cargo']).Valor.sum().reset_index()

total = total[(total['Cargo'] == 'Deputado Federal')]

total.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5516 entries, 0 to 19707
Data columns (total 4 columns):
CPF_candidato     5516 non-null int64
Nome_candidato    5516 non-null object
Cargo             5516 non-null object
Valor             5516 non-null object
dtypes: int64(1), object(3)
memory usage: 150.8+ KB

The Value column I want to round to two decimal places, so I put this command:

total.round({'Valor': 2})

But it didn’t work:

CPF_candidato Nome_candidato  Cargo   Valor
0 1608657 STEFANO AGUIAR DOS SANTOS   Deputado Federal    10000,00548,501675,00500,00400,003750,0010000,...
1 2498316 HENRIQUE EDUARDO BARROSO MOREIRA    Deputado Federal    240,00124,0025,8699,79285,71245,00
6 7331304 CARLOS MAURO CABRAL BENEVIDES   Deputado Federal    3501,4010000,00100000,00200000,00100000,003000...

Someone knows how to do?

  • 1

    You tried to make total = total.round({'Valor': 2})? Another thing: I’m confused with the values exemplified... was it supposed to be a single value? comma is a decimal separator or value separator in a list?

  • Thank you. Yes, I tried the whole command. But you’re right, it’s putting comma where it shouldn’t. The original value comes from cand_doacoes: Value 427489 non-null Object I then tried to convert to float64: cand_doacoes['Value'] = cand_doacoes.Valor.astype('float64') But gave error: Valueerror: could not Convert string to float: '337,5' Must do another type of conversion?

  • 1

    Is not the use of the comma instead of the point for decimal separator the problem? Tried with the values as "337.5"?

  • Thank you, I haven’t tried. Please, in pandas how do I convert a column with commas to dot? ex: 337.5 -> 337.5

  • 1

    It is easier to do this directly on reading the CSV (help here). But you can also do this later by converting to string, changing the comma by dot, and converting back to number (help here). If it works, I suggest you post an answer yourself with the solution.

  • Thank you, I put it up

  • 1

    Nice that it worked! But it was not to edit the question and put in it. It was to use the answer field! : ) Read [Answer], will help you understand how the site works.

Show 2 more comments

1 answer

1


ANSWER THAT WORKED, OF LUIZ VIEIRA - already when reading the CSV you indicate that the decimal is with ",":

cand_doacoes = pd.read_csv("doacoes_csv.csv",sep=';',encoding = 'latin_1', decimal = ",")

And then groupby worked:

total = eleitos_d_doadores.groupby(['CPF_candidato', 'Nome_urna', 'Cargo_x']).Valor.sum().reset_index()

Browser other questions tagged

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