Raj*_*uel 1 python dictionary pandas
两者都适用于 Pandas Series 对象,产生类似的输出:创建字典。但我注意到它们并不是在任何地方都可以互换的。
主要区别在于它将to_dict值映射到内置的 Python 类型:
In [1]: import pandas as pd
In [2]: s = pd.Series([1,2,3],index=['a','b','c'])
In [3]: [(type(k),type(v)) for k,v in s.to_dict().items()]
Out[3]: [(str, int), (str, int), (str, int)]
Run Code Online (Sandbox Code Playgroud)
而dict不会:
In [5]: [(type(k),type(v)) for k,v in dict(s).items()]
Out[5]: [(str, numpy.int64), (str, numpy.int64), (str, numpy.int64)]
Run Code Online (Sandbox Code Playgroud)
注意,dict构造函数适用于pd.Series对象,因为系列实现了映射接口,它们提供了一个.keys方法:
In [6]: s.keys()
Out[6]: Index(['a', 'b', 'c'], dtype='object')
Run Code Online (Sandbox Code Playgroud)
所以dict构造函数天真地把它当作一个映射。您只需要一个.keys方法__getitem__,请参阅:
In [8]: class MyMapping:
...: def keys(self):
...: return [47, 48, 49]
...: def __getitem__(self, item):
...: return chr(item)
...:
In [9]: dict(MyMapping())
Out[9]: {47: '/', 48: '0', 49: '1'}
Run Code Online (Sandbox Code Playgroud)
所以你可以考虑dict构造函数做类似的事情:
for key in mapping.keys():
self[k] = mapping[k]
Run Code Online (Sandbox Code Playgroud)
注意,dict构造函数也接受其他形式,来自help(dict):
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
Run Code Online (Sandbox Code Playgroud)