字符型dataframe转为整形
时间: 2023-06-03 17:05:30 浏览: 36
可以使用 pandas.DataFrame.astype() 方法将字符型的 dataframe 转为整型。例如,将名为 df 的 dataframe 转为整型可以使用以下代码:
```
df = df.astype(int)
```
相关问题
将字符串转为dataframe
以下是将字符串转换为DataFrame的Python代码示例:
```python
import io
import pandas as pd
# 定义字符串
s = '''id height weight score
0 174 55 90
1 152 49 91
2 180 65 82
3 163 61 93
4 192 75 84
5 155 42 75
6 164 50 76'''
# 将字符串转换为DataFrame
df = pd.read_csv(io.StringIO(s), sep='\s+')
# 输出DataFrame
print(df)
```
输出结果为:
```
id height weight score
0 0 174 55 90
1 1 152 49 91
2 2 180 65 82
3 3 163 61 93
4 4 192 75 84
5 5 155 42 75
6 6 164 50 76
```
如何把字符串转为dataframe
要将字符串转换为DataFrame,通常需要使用适当的分隔符将字符串分隔为多个列。可以使用Pandas库中的read_csv()函数来读取分隔符分隔的字符串并将其转换为DataFrame。以下是一个简单的示例:
假设我们有以下字符串:
```
str = "Name,Age,City\nJohn,25,New York\nJane,30,San Francisco\nBob,35,Boston"
```
它包含三个列:Name、Age和City,每个列用逗号分隔。我们可以使用以下代码将其转换为DataFrame:
```python
import pandas as pd
str = "Name,Age,City\nJohn,25,New York\nJane,30,San Francisco\nBob,35,Boston"
df = pd.read_csv(pd.compat.StringIO(str))
print(df)
```
输出:
```
Name Age City
0 John 25 New York
1 Jane 30 San Francisco
2 Bob 35 Boston
```
在这里,我们首先导入了Pandas库,然后使用read_csv()函数从字符串中读取数据。由于数据在字符串中而不是文件中,我们需要使用pd.compat.StringIO()将字符串转换为类似于文件对象的对象,以便Pandas可以读取它。最后,我们打印了DataFrame。