pandas将行值转换为二进制格式

时间:2016-07-12 20:11:31

标签: python pandas

我正在寻找一种方法将数据帧的列值转换为布尔值。在我的数据框中,我有列x,y,z。

我准备了一个参考词典,其中我从每列获得了所有唯一值,用冒号排序和分隔。最后,我将我的dict与数据框连接起来:这是我的dict的样子:{'x':'0:1:10','y':'5:10','z':'0:10: 300' }。

现在将这些已排序的dict值作为参考,我想将列值更改为二进制代码(如下所示,在所需的输出中)。

我的数据框:

_______________________________
 | x | y | z |

 | 0:1:10 | 5:10 | 0:10:300 |
_______________________________
A | 0,1 | 10 | 10,300 |

B | 1 | 5 | 300,0 |

C | 10,0,1 |  | 300,10 |

________________________________

这就是我想要的二进制编码数据帧。

期望的输出:

______________________________
 | x | y | Z |

 | 0:1:10 | 5:10 | 0:10:300 |
______________________________
A | 110 | 01 | 011 |

B | 010 | 10 | 101 |

C | 111 | 00 | 011 |
_______________________________

谢谢,Rtut

1 个答案:

答案 0 :(得分:1)

不确定这是多么可扩展,但这是一个想法:

import sys

from PySide import QtGui, QtCore


title = ["one", "two", "three"]

# i dont have control over the content in my problem, but here is one example:
data = [[" ", "a", "b"], ["c", "d", "e"], ["f", "g", "h"]]

class TableWindow(QtGui.QWidget):

    def __init__(self, parent=None):
        super(TableWindow, self).__init__(parent)
        colcnt = len(data[0])
        rowcnt = len(data)
        self.tablewidget = QtGui.QTableWidget(rowcnt, colcnt)

        # resizing stuff
        vheader = QtGui.QHeaderView(QtCore.Qt.Orientation.Vertical)
        vheader.setResizeMode(QtGui.QHeaderView.ResizeToContents)
        self.tablewidget.setVerticalHeader(vheader)
        hheader = QtGui.QHeaderView(QtCore.Qt.Orientation.Horizontal)
        hheader.setResizeMode(QtGui.QHeaderView.ResizeToContents)
        self.tablewidget.setHorizontalHeader(hheader)
        self.tablewidget.setHorizontalHeaderLabels(title)

        # put the values inside the QTableWidget
        for i in range(rowcnt):
            for j in range(colcnt):
                item = QtGui.QTableWidgetItem(data[i][j])  # it works and shows stuff properly
                print(item.text())  # if you comment this, the code works
                self.tablewidget.setItem(i, j, item)

        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.tablewidget)
        self.setLayout(layout)


def main():
    app = QtGui.QApplication(sys.argv)
    widget = TableWindow()
    widget.show()
    widget.raise_()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()