首页 > 解决方案 > 读取 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,所以我需要使用它来比较其他列。感谢你的帮助。

标签: pythonpandas

解决方案


您也可以尝试这样做。

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()

它将NaN0转换为整数值,然后将所有内容转换为整数值。这样,您将获得所需的值。

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,然后将这些NaNs 转换为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

推荐阅读