【问题标题】:Try to separate words from pandas DataFrame column尝试将单词与 pandas DataFrame 列分开
【发布时间】:2019-11-27 04:08:02
【问题描述】:

我尝试将单词从 DataFrame Columns 中分离出来:

Binary = []
for i in range(0,len(data)):
    if data['attack'][i] == 'normal':
        Binary.append(1)
    else:
        Binary.append(0)
print(len(Binary))

data= pd.DataFrame({'attack':['normal','neptune','ps','normal','neptune']})
print(data)
    attack
0   normal
1  neptune
2       ps
3   normal
4  neptune

我们想将这些列值更改为: ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

   attack
0       1
1       0
2       0
3       1
4       0

只有正常 = 1 否则 0

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    将布尔掩码转换为整数,用于True/False1/0 的映射:

    data['attack'] = data['attack'].eq('normal').astype(int)
    

    或使用numpy.where 指定两个值:

    data['attack'] = np.where(data['attack'].eq('normal'), 1, 0)
    

    print(data)
      attack
    0       1
    1       0
    2       0
    3       1
    4       0
    

    【讨论】:

      【解决方案2】:
      for index, row in data.iteritems():
      for each in row.iteritems():
          if each[1] is "normal":
              print(each[0], "0")
          else:
              print(each[0], "1")
      

      【讨论】:

        猜你喜欢
        • 2019-03-09
        • 1970-01-01
        • 2019-11-02
        • 2020-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-07
        相关资源
        最近更新 更多