pandas字符串转整数
时间: 2023-10-01 22:11:48 浏览: 119
你可以使用 pandas 库中的 astype() 方法将字符串列转换为整数列,示例代码如下:
```python
import pandas as pd
df = pd.DataFrame({'col1': ['1', '2', '3'], 'col2': ['4', '5', '6']})
print(df.dtypes) # 输出数据框的数据类型
df['col1'] = df['col1'].astype(int) # 将 col1 转换为整数类型
print(df.dtypes) # 输出数据框的数据类型(已转换)
```
输出结果如下:
```
col1 object
col2 object
dtype: object
col1 int32
col2 object
dtype: object
```
在代码中,我们首先创建一个包含两个字符串列的数据框,并输出数据类型。然后,我们使用 astype() 方法将 col1 列转换为整数类型,并输出数据类型(已转换)。
相关问题
pandas 如何将整数转换成字符串
在 Pandas 中,可以使用 astype() 方法将整数转换为字符串。例如,假设有一个名为 df 的 DataFrame,其中包含一个名为 "number" 的整数列,可以使用以下代码将其转换为字符串列:
```python
df['number'] = df['number'].astype(str)
```
这将把 "number" 列中的所有整数转换为字符串。
pandas将字符串转整形
可以使用`astype()`方法将字符串转换为整数。
示例代码如下:
```python
import pandas as pd
# 创建一个包含字符串的Series
s = pd.Series(['1', '2', '3', '4', '5'])
# 将字符串转换为整数
s = s.astype(int)
# 输出结果
print(s)
```
输出结果:
```
0 1
1 2
2 3
3 4
4 5
dtype: int64
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)