python - 读取 CSV 并存储在 Pandas 中并将特定列转换为 int
问题描述
我在 csv 中有 2 列并读取 csv 并将其存储在 pandas df 中。一旦数据存储在 df 中,它就成为对象。我想将“A”列转换为 int。例如。以下:
AB 1 2 1 3 3 4 4 5
file_path = "C:\\a.csv"
data = pd.read_csv(file_path,names['A','B'],encoding='latin1', skiprows=[0])
df = pd.DataFrame(data)
print(df.dtypes)
df.dtypes 将 dtype 打印为对象。现在我想将此对象转换为 int64。我做不到。
尝试的事情:
df['A'] = pd.to_numeric(df['A'], errors="coerce") #converted to float64
df['A'] = df['A'].fillna('')
df['A'] = df['A'].astype('int64')
df['A'] = df['A'].astype('str').astype('int64')
它们都没有转换为 int64。因为我需要将此列作为 int,所以我需要使用它来比较其他列。感谢你的帮助。
解决方案
您也可以尝试这样做。
df['A'] = pd.to_numeric(df['A'], errors="coerce").fillna(0).astype(int).to_frame()
上面的代码不会四舍五入为整数。如果你想把数字四舍五入,你可以给这个。.round()
之后fillna(0)
和将.astype(int)
向上舍入。如果您正在寻找要四舍五入到整数的值,这是您的一个选择。
df['A'] = pd.to_numeric(df['A'], errors="coerce").fillna(0).round().astype(int).to_frame()
它将NaN
值0
转换为整数值,然后将所有内容转换为整数值。这样,您将获得所需的值。
import pandas as pd
df = pd.DataFrame({'A':[1.8, 3.3, 5.2, 'Good', 7, 9,2],
'B':['Apple','Banana','Cherry','Donuts','Egg','Fig','Grape']})
print (df)
df['A'] = pd.to_numeric(df['A'], errors="coerce").fillna(0).astype(int).to_frame()
print (df)
这会将值转换df['A']
为数字,同时还将所有字符串设置为NaN
,然后将这些NaN
s 转换为0
然后将其全部转换为 int。由于这是一个系列,您需要将其转换回数据框to_frame()
上述代码的输出是:
原始数据框:
A B
0 1.8 Apple
1 3.3 Banana
2 5.2 Cherry
3 Good Donuts
4 7 Egg
5 9 Fig
6 2 Grape
转换后的数据框:
A B
0 1 Apple
1 3 Banana
2 5 Cherry
3 0 Donuts
4 7 Egg
5 9 Fig
6 2 Grape
推荐阅读
- bootstrap-4 - Bootstrap 4 列系统不适合我
- javascript - 不扩展父级的绝对定位
- python-3.x - Python 错误:TypeError:列表索引必须是整数或切片,而不是 str,
- javascript - 为什么这个 for 循环只打印一个元素?
- json - 从 API 的 json 响应中检索数据
- android - 断言失败:第 190 行第 15 行:'items!= null':不正确
- javascript - How to manage sessions in a small React WebApp?
- python - A python function that finds a number's largest divisor excluding itself
- php - 为什么我的 form_validation 不起作用?错误:未正确填写字段表单
- java - Intellij 终端的行为不同于 Ubuntu 终端的 pulseaudio/pacmd/pactrl 命令