54_Pandas将DataFrame、Series转换为字典 (to_dict)
admin
2024-02-11 10:08:42
0次

54_Pandas将DataFrame、Series转换为字典 (to_dict)

pandas.DataFrame、pandas.Series可以使用to_dict()方法转换为字典(dict类型对象)。

对于pandas.DataFrame,参数orient可以用来指定pandas.DataFrame的行标签索引、列标签列和值如何分配给字典的键和值。

在 pandas.Series 的情况下,它被转换为以标签作为键的字典。

此处解释以下内容。

  • pandas.DataFrame to_dict() 方法
    • 指定字典的格式:Argument orient
    • 转换为 dict 以外的类型:Argument into
  • 从 pandas.DataFrame 的任意两列生成字典
  • pandas.Series to_dict 方法 转换为 dict
    • 转换为 dict 以外的类型:Argument into

创建以下 pandas.DataFrame 作为示例。

import pandas as pd
import pprint
from collections import OrderedDictdf = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['a', 'x', '啊']},index=['row1', 'row2', 'row3'])print(df)
#       col1 col2
# row1     1    a
# row2     2    x
# row3     3    啊

它导入 pprint 以使输出更易于查看,并导入 OrderedDict 以通过参数解释类型规范。

pandas.DataFrame to_dict() 方法

当从 pandas.DataFrame 调用 to_dict() 方法时,默认情况下它将转换为字典(dict 类型对象),如下所示。

d = df.to_dict()pprint.pprint(d)
# {'col1': {'row1': 1, 'row2': 2, 'row3': 3},
#  'col2': {'row1': 'a', 'row2': 'x', 'row3': '啊'}}print(type(d))
# 

指定字典的格式:Argument orient

通过参数orient,可以指定pandas.DataFrame行标签(行名)索引、列标签(列名)列、值值如何分配给字典键和值的格式。

dict

如果 orient=‘dict’,key 是列标签,value 是行标签和值的字典。如果省略了 orient 参数(默认),则为这种格式。

{column -> {index -> value}}

d_dict = df.to_dict(orient='dict')pprint.pprint(d_dict)
# {'col1': {'row1': 1, 'row2': 2, 'row3': 3},
#  'col2': {'row1': 'a', 'row2': 'x', 'row3': '啊'}}print(d_dict['col1'])
# {'row1': 1, 'row2': 2, 'row3': 3}print(type(d_dict['col1']))
# 

list

如果 orient=‘list’,key 是列标签,value 是值列表。行名信息丢失。

{column -> [values]}

d_list = df.to_dict(orient='list')pprint.pprint(d_list)
# {'col1': [1, 2, 3], 'col2': ['a', 'x', '啊']}print(d_list['col1'])
# [1, 2, 3]print(type(d_list['col1']))
# 

series

如果 orient=‘series’,键是列标签,值是 pandas.Series,带有行标签和值。

{column -> Series(values)}

d_series = df.to_dict(orient='series')pprint.pprint(d_series)
# {'col1': row1    1
# row2    2
# row3    3
# Name: col1, dtype: int64,
#  'col2': row1    a
# row2    x
# row3    啊
# Name: col2, dtype: object}print(d_series['col1'])
# row1    1
# row2    2
# row3    3
# Name: col1, dtype: int64print(type(d_series['col1']))
# 

split

如果orient=‘split’,键为’index’、‘columns’、‘data’,values为行标签、列标签和值列表。

{index -> [index], columns -> [columns], data -> [values]}

d_split = df.to_dict(orient='split')pprint.pprint(d_split)
# {'columns': ['col1', 'col2'],
#  'data': [[1, 'a'], [2, 'x'], [3, '啊']],
#  'index': ['row1', 'row2', 'row3']}print(d_split['columns'])
# ['col1', 'col2']print(type(d_split['columns']))
# 

records

如果 orient=‘records’,它将是一个列表,其元素是字典,其中 key 是列标签,value 是值。行名信息丢失。

[{column -> value}, ... , {column -> value}]

l_records = df.to_dict(orient='records')pprint.pprint(l_records)
# [{'col1': 1, 'col2': 'a'}, {'col1': 2, 'col2': 'x'}, {'col1': 3, 'col2': '啊'}]print(type(l_records))
# print(l_records[0])
# {'col1': 1, 'col2': 'a'}print(type(l_records[0]))
# 

index

如果 orient=‘index’,则 key 是行标签,value 是列标签和值的字典。

{index -> {column -> value}}

d_index = df.to_dict(orient='index')pprint.pprint(d_index)
# {'row1': {'col1': 1, 'col2': 'a'},
#  'row2': {'col1': 2, 'col2': 'x'},
#  'row3': {'col1': 3, 'col2': '啊'}}print(d_index['row1'])
# {'col1': 1, 'col2': 'a'}print(type(d_index['row1']))
# 

转换为 dict 以外的类型:Argument into

通过为参数指定类型,它可以转换为子类,例如 OrderedDict,而不是字典(dict 类型)。

字典值value中存储的字典类型也将是指定的类型。

od = df.to_dict(into=OrderedDict)pprint.pprint(od)
# OrderedDict([('col1', OrderedDict([('row1', 1), ('row2', 2), ('row3', 3)])),
#              ('col2',
#               OrderedDict([('row1', 'a'), ('row2', 'x'), ('row3', '啊')]))])print(type(od))
# print(od['col1'])
# OrderedDict([('row1', 1), ('row2', 2), ('row3', 3)])print(type(od['col1']))
# 

从 pandas.DataFrame 的任意两列生成字典

还可以通过从索引和数据列中选择任意两列来创建字典。使用 dict() 和 zip()。

print(df.index)
# Index(['row1', 'row2', 'row3'], dtype='object')print(df['col1'])
# row1    1
# row2    2
# row3    3
# Name: col1, dtype: int64d_col = dict(zip(df.index, df['col1']))print(d_col)
# {'row1': 1, 'row2': 2, 'row3': 3}

pandas.Series to_dict 方法 转换为 dict

以下面的 pandas.Series 为例。

print(df)
#       col1 col2
# row1     1    a
# row2     2    x
# row3     3    啊s = df['col1']
print(s)
# row1    1
# row2    2
# row3    3
# Name: col1, dtype: int64print(type(s))
# 

当你在 pandas.Series 中调用 to_dict() 方法时,会创建一个字典,其中标签是键,值是值。

d = s.to_dict()
print(d)
# {'row1': 1, 'row2': 2, 'row3': 3}print(type(d))
# 

转换为 dict 以外的类型:Argument into

即使使用 pandas.Series 的 to_dict() 方法,通过在参数中指定类型 into,您也可以将其转换为子类,例如 OrderedDict,而不是字典(dict 类型)。

od = df['col1'].to_dict(OrderedDict)
print(od)
# OrderedDict([('row1', 1), ('row2', 2), ('row3', 3)])print(type(od))
# 

相关内容

热门资讯

蜻蜓订购APP贵金属订购非法期...   蜻蜓订购APP以"投资平台"名义对外宣传,主打贵金属期货(订购)交易。该平台一方面强调自身"正规...
悟空订购APP非法期货交易欺骗...   近期,有投资者反映,“悟空订购APP”等平台以白银、贵金属订购为名,宣传所谓“高收益”“低门槛”...
小赢淘金APP期货投资骗局,平...   “小赢淘金”之流,最擅长的就是用“注册送现金”、“充值返券”的糖衣炮弹来引流。别天真地以为那是福...
八方淘金APP非法期货交易欺骗...   警惕!八方生财、每日淘金、小赢淘金、悟空订购、蜻蜓订购、斗金订购等APP均涉嫌非法期货交易!  ...
智易购APP贵金属订购交易骗局...   很多人看到“3元起投”“充值送福利”“操作简单”“随时提现”这类宣传,很容易把智易购APP当成普...
喜玛银庄APP商品订购投资骗局...   喜玛银庄APP白银、铂金“现货订购”骗局警示:无资质平台涉嫌非法期货交易,投资者爆仓后如何维权?...
吉鑫乐享APP炒贵金属订购交易...   近期,多名投资者反映在“吉鑫乐享APP”进行贵金属投资时遭遇严重亏损,甚至血本无归。看似正规的“...
易掘金APP虚假期货投资骗局,...   “易掘金”的APP它打着“高收益、灵活投资”的旗号,宣称通过“商品订购”就能轻松赚钱,吸引了不少...
在大吉订购APP订购交易亏损被...   近期,不少投资者反映在“大吉订购App”上投资白银、铂金等商品遭遇严重亏损。该平台宣称提供现货订...
铂银壹号APP商品订购交易亏损...   许多中小投资者误以为网上的“商品现货订购”是合规合法的理财渠道,殊不知这背后隐藏着巨大的合规风险...
兴鑫淘金APP贵金属订购交易亏...   白银、贵金属或其他商品类投资,除国家批准的正规期货交易场所及持牌期货公司外,市面上大量第三方交易...
铂银掘金APP无资质的违规平台...   铂银掘金等平台的投资者,往往是被“注册送现金”“充值返现券”“首单免亏”等广告话术吸引,进而下载...
八方淘金APP订购交易不合规,...   “八方淘金APP”“铂银掘金APP”“铂银壹号APP”等软件被指以“现货订购”为名,实际采用高杠...
在指尖订购APP订购商品亏损被...   指尖订购APP这类平台,表面是“订购交易”,实则是披着电商外衣的非法期货陷阱。绝大多数投资者被蒙...
在犀贝易购APP做商品订购交易...   市面上打着“现货投资”“贵金属交易”旗号的APP并不少,但真正合规、受监管的平台并不多。犀贝易购...
易达淘金APP虚假商品订购交易...   易达淘金APP存在严重的虚假宣传与违规交易行为。该平台打着“商品订购”的旗号,实则通过不合规的交...
大浪淘金APP白银订购亏损被骗...   大浪淘金APP最隐蔽的套路,在于其完全封闭的内盘交易系统。表面上,它宣称与国际贵金属市场接轨;实...
一品好购APP上订购白银出现亏...   一品好购APP原名“一品订购”,运营方为上海宝智未来信息技术有限公司。近期不少投资者反映在该平台...
九州订购APP贵金属订购投资骗...   九州订购APP正通过抖.音、快手、今日头条等平台大量投放投资广告,用“5元起投”“充值返现”“0...
坚锅淘金APP交易软件并不正规...   当前,市面上大量所谓的“现货商城订购”交易软件,早已偏离了正常的实物商品买卖,演变为高杠杆、高手...