想要将objectny中具有?值的数据框转换为010

这是df.head()

df.head()
party   infants water   budget  physician   salvador    religious   satellite   aid missile immigration synfuels    education   superfund   crime   duty_free_exports   eaa_rsa
0   republican  n   y   n   y   y   y   n   n   n   y   ?   y   y   y   n   y
1   republican  n   y   n   y   y   y   n   n   n   n   n   y   y   y   n   ?
2   democrat    ?   y   y   ?   y   y   n   n   n   n   y   n   y   y   n   n
3   democrat    n   y   y   n   ?   y   n   n   n   n   y   n   y   n   n   y
4   democrat    y   y   y   n   y   y   n   n   n   n   y   ?   y   y   y   y


我尝试使用一个简单的for循环:

for names in df.columns.values:
    df.names.replace(('n', 'y'), (0, 1), inplace=True)
    df.names.replace('?', 0, inplace=True)


但这给我一个AttributeError: 'DataFrame' object has no attribute 'names'

请分享给我将object值转换为int值的任何想法。

最佳答案

我认为您可以在没有DataFrame.replace的情况下使用inplace

df = df.replace(('n','?','y'), (0,0,1))
#alternative
df = df.replace({'n':0,'?':0,'y':1})




print (df)
        party  infants  water  budget  physician  salvador  religious  \
0  republican        0      1       0          1         1          1
1  republican        0      1       0          1         1          1
2    democrat        0      1       1          0         1          1
3    democrat        0      1       1          0         0          1
4    democrat        1      1       1          0         1          1

   satellite  aid  missile  immigration  synfuels  education  superfund  \
0          0    0        0            1         0          1          1
1          0    0        0            0         0          1          1
2          0    0        0            0         1          0          1
3          0    0        0            0         1          0          1
4          0    0        0            0         1          0          1

   crime  duty_free_exports  eaa_rsa
0      1                  0        1
1      1                  0        0
2      1                  0        0
3      0                  0        1
4      1                  1        1


通常不建议使用inplace-link


  熊猫核心团队不鼓励使用inplace参数,最终将不推荐使用它(这意味着“计划从库中删除”)。原因如下:
  
  就位在方法链中不起作用。
  与名称所暗示的相反,使用inplace通常不会阻止创建副本。
  删除inplace选项将降低pandas代码库的复杂性。


在代码中,names是列名,您只想替换该列的值:

df.names.replace


错误意味着没有列names


  AttributeError:“ DataFrame”对象没有属性“名称”

关于python - 循环转换Pandas Dataframes值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59526981/

10-11 16:41