读取CSV并存储在Pandas中,并将特定列转换为int

2024-05-06 01:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我在csv中有2列,读取csv并将其存储在df中。一旦数据存储在df中,它就成为对象。我想将“A”列转换为int。例如:

A B 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将数据类型打印为对象。现在我想把这个对象转换成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,所以我需要使用它来比较其他列。谢谢你的帮助


Tags: csvto数据path对象dfreaddata
2条回答

尽管这很难看,但它仍然有效:

np.floor(pd.to_numeric(df['A'], errors='coerce')).astype(pd.Int64Dtype())

您也可以尝试这样做

df['A'] = pd.to_numeric(df['A'], errors="coerce").fillna(0).astype(int).to_frame()

上述代码不舍入为整数。如果你想把数字四舍五入,你可以给这个。在fillna(0).astype(int)之后的.round()将向上舍入。如果您希望将值向上舍入为整数,则这是一个选项

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转换为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

相关问题 更多 >