[898] Convert the data type of a DataFrame column

发布时间 2023-10-10 08:50:05作者: McDelfino

In Pandas, you can convert the data type of a DataFrame column to a string data type using the .astype() method. Here's how to do it:

import pandas as pd

# Create a sample DataFrame
data = {'A': [1, 2, 3, 4, 5],
        'B': [10.1, 20.2, 30.3, 40.4, 50.5]}

df = pd.DataFrame(data)

# Convert column 'A' to string data type
df['A'] = df['A'].astype(str)

# Check the data types of the DataFrame
print(df.dtypes)

In this example, we first create a DataFrame df with columns 'A' and 'B'. Then, we use .astype(str) to convert the 'A' column to a string data type. Finally, we check the data types of the DataFrame to confirm that column 'A' is now of type 'object' (which is Pandas' representation of strings).

The result will show that the 'A' column has been converted to a string data type:

A     object
B    float64
dtype: object

Now, the values in the 'A' column are treated as strings, and you can perform string operations and manipulations on them.