Data Type बदलना
Columns को सही type में convert करें ताकि sorting, maths, और dates सही behave करें।
In this page:
Syntax
df["column"] = df["column"].astype(type)
df["column"] = pd.to_numeric(df["column"], errors="coerce")
Data Type Conversion
astype एक column का dtype बदलता है। errors="coerce" वाला pd.to_numeric bad values को fail होने की बजाय NaN बना देता है, और pd.to_datetime date strings parse करता है। missing values के साथ integers रखने के लिए nullable "Int64" dtype इस्तेमाल करें।
Note:
dirty data के लिए errors="coerce" आपका friend है।
उदाहरण: Data type conversion
import pandas as pd
df = pd.DataFrame({"n": ["1", "2", "oops"], "d": ["2024-01-05", "2024-02-10", "2024-03-15"]})
df["n"] = pd.to_numeric(df["n"], errors="coerce")
df["d"] = pd.to_datetime(df["d"])
print(df)
print(df.dtypes)
print(df["n"].astype("Int64"))
# Output:
# n d
# 0 1.0 2024-01-05
# 1 2.0 2024-02-10
# 2 NaN 2024-03-15
# n float64
# d datetime64[ns]
# dtype: object
# 0 1
# 1 2
# 2 <NA>
# Name: n, dtype: Int64
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- NaN वाले एक column को int में convert करना
- bad values पर coerce इस्तेमाल न करना
- एक ambiguous day/month order में dates parse करना
चैप्टर सारांश
- astype dtypes convert करता है
- to_numeric coerce junk को NaN बनाता है
- to_datetime dates parse करता है
- Int64 missing integers allow करता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: