👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!
I want to set the dtype
s of multiple columns in pd.Dataframe
(I have a file that I"ve had to manually parse into a list of lists, as the file was not amenable for pd.read_csv
)
import pandas as pd
print pd.DataFrame([["a","1"],["b","2"]],
dtype={"x":"object","y":"int"},
columns=["x","y"])
I get
ValueError: entry not a 2- or 3- tuple
The only way I can set them is by looping through each column variable and recasting with astype
.
dtypes = {"x":"object","y":"int"}
mydata = pd.DataFrame([["a","1"],["b","2"]],
columns=["x","y"])
for c in mydata.columns:
mydata[c] = mydata[c].astype(dtypes[c])
print mydata["y"].dtype #=> int64
Is there a better way?
👻 Read also: what is the best laptop for engineering students?
We hope this article has helped you to resolve the problem. Apart from Assign pandas dataframe column dtypes, check other ast Python module-related topics.
Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.
By the way, this material is also available in other languages:
- Italiano Assign pandas dataframe column dtypes
- Deutsch Assign pandas dataframe column dtypes
- Français Assign pandas dataframe column dtypes
- Español Assign pandas dataframe column dtypes
- Türk Assign pandas dataframe column dtypes
- Русский Assign pandas dataframe column dtypes
- Português Assign pandas dataframe column dtypes
- Polski Assign pandas dataframe column dtypes
- Nederlandse Assign pandas dataframe column dtypes
- 中文 Assign pandas dataframe column dtypes
- 한국어 Assign pandas dataframe column dtypes
- 日本語 Assign pandas dataframe column dtypes
- हिन्दी Assign pandas dataframe column dtypes
Vigrinia | 2023-01-31
Maybe there are another answers? What Assign pandas dataframe column dtypes exactly means?. I am just not quite sure it is the best method
Rome | 2023-01-31
Maybe there are another answers? What Assign pandas dataframe column dtypes exactly means?. Checked yesterday, it works!
California | 2023-01-31
Simply put and clear. Thank you for sharing. Assign pandas dataframe column dtypes and other issues with re Python module was always my weak point 😁. Checked yesterday, it works!