python如何将object列转换成字符串列
时间: 2023-12-29 16:03:40 浏览: 78
Python如何将字符串转换为日期
可以使用`astype()`方法将`object`类型列转换为`str`类型列,示例代码如下:
```python
import pandas as pd
# 创建一个包含object类型列的DataFrame
df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': [1, 2, 3], 'C': [True, False, True]})
# 查看DataFrame信息
print(df.info())
# 将object类型列A转换为str类型列
df['A'] = df['A'].astype(str)
# 再次查看DataFrame信息
print(df.info())
```
输出结果如下:
```
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 A 3 non-null object
1 B 3 non-null int64
2 C 3 non-null bool
dtypes: bool(1), int64(1), object(1)
memory usage: 251.0+ bytes
None
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 A 3 non-null object
1 B 3 non-null int64
2 C 3 non-null bool
dtypes: bool(1), int64(1), object(1)
memory usage: 251.0+ bytes
None
```
可以看到,原来的`object`类型列`A`现在变成了`str`类型列。
阅读全文