Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

I have the following DataFrame from a SQL query:

(Pdb) pp total_rows

     ColumnID  RespondentCount

0          -1                2

1  3030096843                1

2  3030096845                1

and I want to pivot it like this:

total_data = total_rows.pivot_table(cols=['ColumnID'])

(Pdb) pp total_data

ColumnID         -1            3030096843   3030096845

RespondentCount            2            1            1

[1 rows x 3 columns]

total_rows.pivot_table(cols=['ColumnID']).to_dict('records')[0]

{3030096843: 1, 3030096845: 1, -1: 2}

but I want to make sure the 303 columns are casted as strings instead of integers so that I get this:

{'3030096843': 1, '3030096845': 1, -1: 2}

1 Answer

0 votes
by (41.4k points)

Use the below line of code that will particularly be useful to convert the multiple columns to string instead of just single column:

 import numpy as np

 import pandas as pd

 df = pd.DataFrame({

  'A': [20, 30.0, np.nan],

  'B': ["a45a", "a3", "b1"],

  'C': [10, 5, np.nan]})

 df.dtypes ## Current datatype

Out: 

A    float64

B     object

C    float64

dtype: object

## Multiple columns string conversion

 df[["A", "C"]] = df[["A", "C"]].astype(str) 

 df.dtypes ## Updated datatype after string conversion

Out: 

A    object

B    object

C    object

dtype: object

If you want to learn more about Pandas then visit this Python Course designed by the industrial experts.

Browse Categories

...