简体   繁体   English

将列从float转换为int时收到KeyError

[英]Receiving KeyError when converting a column from float to int

created a pandas data frame using read_csv. 使用read_csv创建了一个熊猫数据框。

I then changed the column name of the 0th column from 'Unnamed' to 'Experiment_Number' . 然后,将第0列的列名从'Unnamed'更改为'Experiment_Number'

The values in this column are floating point numbers and I've been trying to convert them to integers using: 此列中的值是浮点数,我一直在尝试使用以下方法将它们转换为整数:

df['Experiment_Number'] = df['Experiment_Number'].astype(int)

I get this error: 我收到此错误:

KeyError: 'Experiment_Number' KeyError:“ Experiment_Number”

I've been trying every way since yesterday, for example also 从昨天开始我一直在尝试各种方法,例如

df['Experiment_Number'] = df.astype({'Experiment_Number': int})

and many other variations. 和许多其他变体。

Can someone please help, I'm new using pandas and this close to giving up on this :( 有人可以帮忙吗,我是新来的熊猫人,这简直就是放弃:(

Any help will be appreciated 任何帮助将不胜感激

I had used this for renaming the column before: 我以前曾用它来重命名该列:

 df.columns.values[0] = 'Experiment_Number' 

This should have worked. 这应该起作用了。 The fact that it didn't can only mean there were special characters/unprintable characters in your column names. 事实并非仅仅意味着您的列名中包含特殊字符/不可打印字符。

I can offer another possible suggestion, using df.rename : 我可以使用df.rename提供另一个建议:

df = df.rename(columns={df.columns[0] : 'Experiment_Number'})

You can convert the type during your read_csv() call then rename it afterward. 您可以在read_csv()调用期间转换类型,然后再重命名。 As in

df = pandas.read_csv(filename, 
                     dtype = {'Unnamed': 'float'}, # inform read_csv this field is float
                     converters = {'Unnamed': int}) # apply the int() function
df.rename(columns = {'Unnamed' : 'Experiment_Number'}, inplace=True)

The dtype is not strictly necessary, because the converter will override it in this case, but it is wise to get in the habit of always providing a dtype for every field of your input. dtype不是严格必需的,因为在这种情况下转换器将覆盖它,但是明智的做法是养成始终为输入的每个字段提供dtype的习惯。 It is annoying, for example, how pandas treats integers as floats by default. 令人讨厌的是,例如,pandas默认如何将整数视为浮点数。 Also, you may later remove the converters option without worry, if you specified dtype. 另外,如果您指定了dtype,则以后可以不用担心就删除converters选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM