I have a dictionary with keys ranging from 0 to 9000. Every key has a 0 or 1 value. I want to transform the dictionary into a dataframe with 1 column.
Expected output:
0
0
1
0
1
0
0
Edit:
I think the datatype needs to be an array. An array with 9000 values in total, each value is a 0 or a 1.
Edit2:
Problem was solved with the solution from the comments:
[dkt[k] for k in sorted(dkt.keys())]
答案 0 :(得分:1)
There is no int32
object in Python, only int
. Have a look at the answers to the question "sys.getsizeof(int)" returns an unreasonably large value? or PEP 237 -- Unifying Long Integers and Integers for more information on Python type int
and its memory size.
Of course, you still can convert your bits in the dict
to an int
:
d = {
0: 1,
1: 0,
2: 1
}
bin_list = [d[key] for key in sorted(d)]
bin_str = "".join(map(str, bin_list))
number = int(bin_str, 2)
print("{} -> {} -> {} -> {}".format(d, bin_list, bin_str, number))
Which prints for the example bits of 101 = 1*2^2 + 0*2^1 + 1*2^0 = 4 + 0 + 1 = 5
:
{0: 1, 1: 0, 2: 1} -> [1, 0, 1] -> 101 -> 5
答案 1 :(得分:0)
Are you trying to coerce each value in the dictionary?
$ python
Python 3.7.2 (default, Dec 27 2018, 07:35:06)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {'a': 1, 'b': 0, 'c': '1', 'd': '0'}
>>> for key, value in d.items():
... int_value = int(value)
... print(f'{int_value} ({type(int_value)})')
...
1 (<class 'int'>)
0 (<class 'int'>)
1 (<class 'int'>)
0 (<class 'int'>)