如何在Pandas DF中将具有特定值的特定列设置为新值?

时间:2018-04-16 06:33:31

标签: python pandas for-loop conditional

我导入了一个包含两列ID和Bee_type的CSV文件。 bee_type有两种类型 - 大黄蜂和蜜蜂。我试图将它们转换为数字而不是名称;而不是大黄蜂它说1。

但是,我的代码将所有内容都设置为1.如何将ID列保留为原始值并仅更改bee_type列?

       @Override
public void onActivityResult(int req, int res, Intent imageIntent) {
    super.onActivityResult(req, res, imageIntent);

    switch (req) {
        case SELECT_ICON:
            if (res == RESULT_OK) {
                try {
                    final Uri iconUri = imageIntent.getData();
                    final String imgUri = iconUri.toString();
                    final InputStream iconStream = getContentResolver().openInputStream(iconUri);
                    final Bitmap selectedIcon = BitmapFactory.decodeStream(iconStream);
                    imageView.setImageBitmap(selectedIcon);

                    saveButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View arg0) {
                            String tname = text1.getText().toString();
                            String date = textView.getText().toString();
                            String priority = spinner1.getSelectedItem().toString();
                            String notes = text2.getText().toString();
                            String path = imgUri;

                            dbHelper.addTask(new Task(tname, date, priority, notes, path));
                            Toast.makeText(getApplicationContext(), "Success!!!", Toast.LENGTH_LONG).show();
                            TaskListActivity.tasklist.RefreshList();
                            finish();
                        }
                    });
                } catch (FileNotFoundException err) {
                    err.printStackTrace();
                }
            }
    }
}

2 个答案:

答案 0 :(得分:2)

如果只存在2个可能的值,我相信你需要map字典:

let appearance = SMSegmentAppearance()
            appearance.segmentOnSelectionColour =  UIColor(red: 1, green: 0.8706, blue: 0.7608, alpha: 1.0)
            appearance.segmentOffSelectionColour = UIColor(red: 1, green: 0.8706, blue: 0.7608, alpha: 1.0)
            appearance.titleOnSelectionFont = UIFont.systemFont(ofSize: 25.0)
//            segmentControlView.font = UIFont(name: "Avenir-Black", size: 12)
            appearance.titleOffSelectionFont = UIFont.systemFont(ofSize: 25.0)
            appearance.contentVerticalMargin = 10

            /*
             Init SMsegmentView
             Set divider colour and width here if there is a need
             */
            let segmentFrame = CGRect(x: self.margin, y: 5, width: self.segmentControlView.frame.size.width - self.margin*8, height: 50.0)
            self.segmentView = SMSegmentView(frame: segmentFrame, dividerColour: UIColor(red: 1, green: 0.8706, blue: 0.7608, alpha: 1.0), dividerWidth: 1.0, segmentAppearance: appearance)
            self.segmentView.backgroundColor = UIColor(red: 1, green: 0.8706, blue: 0.7608, alpha: 1.0)

            self.segmentView.layer.cornerRadius = 5.0
            self.segmentView.layer.borderColor = UIColor(red: 1, green: 0.8706, blue: 0.7608, alpha: 1.0).cgColor
            self.segmentView.layer.borderWidth = 1.0


            self.segmentView.addTarget(self, action: #selector(selectSegmentInSegmentView(segmentView:)), for: .valueChanged)

            self.segmentView.addSegmentWithTitle("All", onSelectionImage: UIImage(named: ""), offSelectionImage: UIImage(named: ""))

            self.segmentView.addSegmentWithTitle("Pending", onSelectionImage: UIImage(named: ""), offSelectionImage: UIImage(named: ""))

                self.segmentView.addSegmentWithTitle("Finished", onSelectionImage: UIImage(named: ""), offSelectionImage: UIImage(named: ""))

                self.segmentView.addSegmentWithTitle("Expired", onSelectionImage: UIImage(named: ""), offSelectionImage: UIImage(named: ""))

//            var ownerNames = [String]()
//
//            if  fetchedToDoItems.count > 0 {
//                for item in fetchedToDoItems {
//                    if item.houseNo == loggedInUserHouseNumber &&
//                        !ownerNames.contains(item.ownerName!) {
//                        ownerNames.append(item.ownerName!)
//                    }
//                }
//
//                for name in ownerNames {
//                    // Add segments
//                    self.segmentView.addSegmentWithTitle(name, onSelectionImage: UIImage(named: ""), offSelectionImage: UIImage(named: ""))
//                }
//
//            }

            // Set segment with index 0 as selected by default
            self.segmentView.selectedSegmentIndex = 0
            self.segmentControlView.addSubview(self.segmentView)

另一个解决方案是使用numpy.where - 按条件设置值:

labels['bee_type'] = labels['bee_type'].map({'bumble_bee': 1, 'honey_bee': 2})

您的代码有效,但为了提高性能,请稍微修改一下 - 删除循环并添加labels['bee_type'] = np.where(labels['bee_type'] == 'bumble_bee', 1, 2)

loc

<强>示例

labels.loc[labels['bee_type'] == 'bumble_bee'] = 1
print (labels)
   ID   bee_type
0   1          1
1   1  honey_bee
2   1          1
3   3  honey_bee
4   1          1

答案 1 :(得分:0)

据我所知,您希望将名称转换为数字。如果是那个场景,请尝试使用LabelEncoder。可以找到详细的文档sklearn LabelEncoder