【发布时间】:2018-09-17 22:11:54
【问题描述】:
我正在尝试从我的 pandas DataFrame 创建默认字典,但 to_dict() 方法会在我要写入的列的值周围创建不需要的方括号。示例代码如下:
# Create DF
my_df = pd.DataFrame({'numbers': (1, 2, 3, 4, 5), 'letters': ('a', 'b', 'c', 'd', 'e')})
# Create dictionary from the DF
my_dict = my_df.set_index('numbers').T.to_dict('list')
# Create collections dictionary
my_collections_dict = collections.defaultdict(int, my_dict)
结果:
defaultdict(int, {1: ['a'], 2: ['b'], 3: ['c'], 4: ['d'], 5: ['e']})
我想要的是:
defaultdict(int, {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'})
如何获取“纯”列值?
【问题讨论】:
-
您将
dict传递给defaultdict构造函数,因此它将返回等效的defaultdict。
标签: python pandas dictionary