Sometimes, you just have to use a for-loop:
for col in ['parks', 'playgrounds', 'sports', 'roading']:
public[col] = public[col].astype('category')
Answer from unutbu on Stack Overflow Top answer 1 of 8
163
Sometimes, you just have to use a for-loop:
for col in ['parks', 'playgrounds', 'sports', 'roading']:
public[col] = public[col].astype('category')
2 of 8
83
No need for loops, Pandas can do it directly now, just pass a list of columns you want to convert and Pandas will convert them all.
cols = ['parks', 'playgrounds', 'sports', 'roading']
public[cols] = public[cols].astype('category')
df = pd.DataFrame({'a': ['a', 'b', 'c'], 'b': ['c', 'd', 'e']})
>> a b
>> 0 a c
>> 1 b d
>> 2 c e
df.dtypes
>> a object
>> b object
>> dtype: object
df[df.columns] = df[df.columns].astype('category')
df.dtypes
>> a category
>> b category
>> dtype: object
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.astype.html
pandas.DataFrame.astype — pandas 3.0.3 documentation
Use a str, numpy.dtype, pandas.ExtensionDtype or Python type to cast entire pandas object to the same type. Alternatively, use a mapping, e.g. {col: dtype, …}, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame’s columns to column-specific types.
python - How to change datatype of multiple columns in pandas - Stack Overflow
I'm trying to run a Random Forest on a pandas dataframe. I know there are no nulls or infinities in the dataframe but continually get a ValueError when I fit the model. Presumably this is because I... More on stackoverflow.com
How do you guys handle pandas and its sh*tty data type inference
I feel like y'all need to learn how to read docs, you can (and should) specify your schema beforehand, which you can do by setting dtype param on read_csv to a dictionary in the form of "column_name": pandas_type. Docs More on reddit.com
[pandas] ValueError: Columns must be same length as key
Your code is trying to assign a whole dataframe to a single column. If you only want to assign the first column of that frame do this: df['First'] = df['First'].str.split(expand=True)[0] More on reddit.com
Unable to convert a pandas object to a string in my DataFrame
object is just the dtype pandas uses for columns that contain values of type str (and many other Python types). The actual values themselves are still strings: import pandas as pd df = pd.DataFrame([["hello"], ["world"]], columns=["words"]) df.dtypes >>> words object dtype: object type(df.loc[0, "words"]) >>> Using .astype(str) does convert all values to string if they aren't already, but it doesn't change the column dtype by design. The only way around this is to use pandas's own string type via .astype("string"), but that's different from the str type, obviously. What exactly are the issues you are facing with the API? More on reddit.com
Can I use astype() to convert multiple columns at once?
Yes, pass a dictionary to astype(), like df.astype({'col1': 'int32', 'col2': 'float64'}), to convert multiple columns in one step.
upgrad.com
upgrad.com › home › blog › data science › a comprehensive guide to pandas dataframe astype()
A Comprehensive Guide to Pandas DataFrame astype()
Can astype() handle conversions of string-based categorical columns?
Yes, convert string-based columns to category with astype('category') to optimize memory usage and speed up operations like groupby().
upgrad.com
upgrad.com › home › blog › data science › a comprehensive guide to pandas dataframe astype()
A Comprehensive Guide to Pandas DataFrame astype()
How can I prevent astype() from modifying the original DataFrame?
Set copy=True (default) to avoid modifying the original DataFrame. Use copy=False to modify in place.
upgrad.com
upgrad.com › home › blog › data science › a comprehensive guide to pandas dataframe astype()
A Comprehensive Guide to Pandas DataFrame astype()
Videos
04:32
Python Basics Tutorial Pandas Astype Method - YouTube
08:18
How to Change Column Types in Pandas - YouTube
02:33
Select (Multiple) Columns in DataFrame | Pandas - YouTube
08:33
Pandas QUERY // Examples of pandas query with MULTIPLE CONDITIONS ...
How to Convert Multiple Columns from String to Integer in a ...
Pandasdataframe
pandasdataframe.com › pandas-astype-multiple-columns.html
Pandas astype Multiple Columns-Pandas Dataframe
Let’s dive into some detailed examples to illustrate how to use the astype method to convert multiple columns in a Pandas DataFrame.
YouTube
youtube.com › kimberly fessel
Update pandas data types // Change data types of multiple columns with Python pandas astype - YouTube
Change the data types of your Python pandas dataframes and series columns using pandas astype method. This video from my "Pandas Tips" series demonstrates ho...
Published December 20, 2023 Views 1K
Programiz
programiz.com › python-programming › pandas › methods › astype
Pandas astype()
import pandas as pd # sample DataFrame data = {'A': ['1', '2', '3'], 'B': ['4', '5', '6']} df = pd.DataFrame(data) # convert data types of columns A and B df = df.astype({'A': int, 'B': float}) print(df) Output · A B 0 1 4.0 1 2 5.0 2 3 6.0 · In this example, we passed a dictionary in the format {col_name: dtype, ...} to the astype() method to convert data types of multiple columns.
Python Examples
pythonexamples.org › how-to-change-datatype-of-columns-in-pandas-dataframe
How to Change Datatype of Columns in Pandas DataFrame?
All, we have to do is provide more column_name:datatype key:value pairs in the argument to astype() method. In the following program, we shall change the datatype of column a to float, and b to int8. import pandas as pd import numpy as np #initialize a dataframe df = pd.DataFrame( [[21, 72, ...
Sentry
sentry.io › sentry answers › python › change a column type in a dataframe in python pandas
Change a column type in a DataFrame in Python Pandas | Sentry
import pandas as pd # Create and print DataFrame df = pd.DataFrame({ 'A': ['1', '2', '3'], 'B': ['4', '5', '6'], 'C': ['7', '8', '9'] }) print(df) # Print data types of each column in DataFrame print("\n") print(df.dtypes) # Change column A's values to floats df['A'] = df['A'].astype(float) # Change column B and C's values to integers df = df.astype({'B': int, 'C': int}) print("\nConverted:\n") # Print altered DataFrame print(df) # Print data types of each column in DataFrame print("\n") print(df.dtypes)
GeeksforGeeks
geeksforgeeks.org › pandas › change-data-type-for-one-or-more-columns-in-pandas-dataframe
Change Data Type for one or more columns in Pandas Dataframe - GeeksforGeeks
July 11, 2025 - You can use this method to cast columns to any specified data type, such as converting them to a string (object) type. ... import pandas as pd df = pd.DataFrame({ 'A': [1, 2, 3, 4, 5], 'B': ['a', 'b', 'c', 'd', 'e'], 'C': [1.1, '1.0', '1.3', 2, 5] }) df = df.astype(str) print(df.dtypes)
Medium
medium.com › @filip.sekan › 3-ways-how-to-update-data-type-of-columns-in-pandas-97ddb5f32ae4
3 ways how to update data type of columns in Pandas | by Filip Sekan | Medium
February 3, 2023 - Here’s an example of how to use the astype() method to change the data type of a column in a Pandas dataframe: ... As we can see, the data type of the ‘age’ column has been changed to ‘object’, which is the data type for strings in Pandas. It’s also possible to change the data type of multiple columns in a dataframe using the astype() method.
Sharp Sight
sharpsight.ai › blog › pandas-astype
How to Use the Pandas Astype Function in Python - Sharp Sight
March 22, 2022 - In this tutorial, I’ll explain how to use the Pandas astype function to modify the datatype of Pandas dataframe columns and Pandas objects. I’ll explain what the technique does, explain the syntax, and show you step-by-step examples. If you need something specific, you can click on any ...
Seaborn
deeplearningnerds.com › pandas-change-column-types-of-a-dataframe
Pandas - Change Column Types of a DataFrame
March 4, 2024 - # Convert string to integer df["users"] = df["users"].astype(int) # Convert string to boolean df["backend"] = df["backend"].map({"true": True, "false": False}) # Convert string to datetime df["date"] = pd.to_datetime(df["date"]) # Print schema df.dtypes · As you can see, the columns "users", "backend" and "date" now have the desired data types. Congratulations! Now you are one step closer to become an AI Expert. You have seen that it is very easy to change column types of a Pandas DataFrame.
Top answer 1 of 3
65
You can use df.astype() with a dictionary for the columns you want to change with the corresponding dtype.
df = df.astype({'col1': 'object', 'col2': 'int'})
2 of 3
14
To change the dtypes of all float64 columns to float32 columns try the following:
for column in df.columns:
if df[column].dtype == 'float64':
df[column] = df[column].astype(np.float32)
TutorialsPoint
tutorialspoint.com › change-data-type-for-one-or-more-columns-in-pandas-dataframe
Change Data Type for one or more columns in Pandas Dataframe
August 23, 2019 - import pandas as pd # Example dataframe df = pd.DataFrame({ 'DayNo': [1, 2, 3, 4, 5,6,7], 'Name': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu','Fri','Sat'], 'Qty': [2.6, 5, 11.8, 2, 5.6,0,0.25]}) df_str = df.astype(str) print(df_str.dtypes) #Applying conversion print("After Conversion:") df_num = pd.to_numeric(df_str.DayNo) print('DayNo:',df_num.dtypes) Running the above code gives us the following result − · DayNo object Name object Qty object dtype: object After Conversion: DayNo: int64 · It is a method of soft conversion where we convert columns of a DataFrame that have an object datatype to a mo