how to convert all columns in the .csv file from numeric to categorical in Python
<pre><code>data[].astype('categorical')
</code></pre>

<p>there are 51 columns in my csv file, do I need to add all 51 column namesin the square brackets?
I need all 51 columns which are in int64 to be categorical </p>

<p>You can get the column names into a list, then loop to change the type of each column.</p>

<pre><code>import pandas as pd
import numpy as np

# create example dataframe
cats = ['A', 'B', 'C', 'D', 'E']

int_matrix = np.random.randint(10, size=(7,5))

df = pd.DataFrame(data = int_matrix, columns=cats)

print("Original example data\n")
print(df)
print(df.dtypes)

# get column names of data frame in a list
col_names = list(df)
print("\nNames of dataframe columns")
print(col_names)

# loop to change each column to category type
for col in col_names:
    df[col] = df[col].astype('category',copy=False)

print("\nExample data changed to category type")
print(df)
print(df.dtypes)
</code></pre>

<p>The output of this little program is:</p>

<pre><code>Original example data

   A  B  C  D  E
0  0  4  9  2  9
1  2  5  2  4  1
2  1  1  0  5  7
3  1  2  5  4  0
4  9  2  6  5  3
5  3  3  2  1  7
6  6  0  8  7  3
A    int32
B    int32
C    int32
D    int32
E    int32
dtype: object

Names of dataframe columns
['A', 'B', 'C', 'D', 'E']

Example data changed to category type
   A  B  C  D  E
0  0  4  9  2  9
1  2  5  2  4  1
2  1  1  0  5  7
3  1  2  5  4  0
4  9  2  6  5  3
5  3  3  2  1  7
6  6  0  8  7  3
A    category
B    category
C    category
D    category
E    category
dtype: object
</code></pre>

python