循环转换Pandas Dataframes值

时间:2019-12-30 07:07:30

标签: python pandas

希望将$.each(data, function (element, index) { Items += element + ","; element; }); objectn中具有y值的数据帧转换为?0和{{ 1}}

这是1

0

我尝试使用一个简单的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'值的任何想法。

1 个答案:

答案 0 :(得分:1)

我认为您可以使用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

  

pandas核心团队不鼓励使用 inplace 参数,最终将不推荐使用该参数(这意味着“计划从库中删除”)。原因如下:

     

就地在方法链中不起作用。
  与名称所暗示的相反,使用 inplace 通常不会阻止创建副本。
  删除 inplace 选项将降低熊猫代码库的复杂性。

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

df.names.replace

错误意味着没有列names

  

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