Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert datatype after add row end of the dataframe with loc

I have this dataframe.

data = {"score":[10, 54, 65, 23, 94, 40, 79, 89], "code":[2, 6, 8, 6, 4, 9, 1, 5], "percentage":[0.12, 0.65, 0.03, 0.96, 0.43, 0.76, 0.23, 0.93]}
df = pd.DataFrame(data)
print(df)

Output:

   score  code  percentage
0     10     2        0.12
1     54     6        0.65
2     65     8        0.03
3     23     6        0.96
4     94     4        0.43
5     40     9        0.76
6     79     1        0.23
7     89     5        0.93

dataframe have been changed datatype to float after add row end of the dataframe with loc

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df.loc[len(df)] = [43, 9, 0.55]
print(df)

Output:

   score  code  percentage
0   10.0   2.0        0.12
1   54.0   6.0        0.65
2   65.0   8.0        0.03
3   23.0   6.0        0.96
4   94.0   4.0        0.43
5   40.0   9.0        0.76
6   79.0   1.0        0.23
7   89.0   5.0        0.93
8   43.0   9.0        0.55

why? can any one help me?

>Solution :

This assignment handles your list as Series, which has a unique dtype. Thus the 0.55 forces the whole row to be float.

You can use concat:

pd.concat([df, pd.DataFrame([[43, 9, 0.55]], columns=df.columns, index=[len(df)])])

output:

   score  code  percentage
0     10     2        0.12
1     54     6        0.65
2     65     8        0.03
3     23     6        0.96
4     94     4        0.43
5     40     9        0.76
6     79     1        0.23
7     89     5        0.93
8     43     9        0.00
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading