pandas 如何在Python中将两列 Dataframe 转换为orderedDict?

drnojrws  于 2023-01-19  发布在  Python
关注(0)|答案(2)|浏览(236)

我有一个名为tableTest的表,如下所示:
| 开始日期|结束日期|
| - ------|- ------|
| 二〇二二年十二月十五日|二〇二二年十二月十八日|
| 二〇二二年十二月十九日|二〇二二年十二月二十一日|
| 二〇二二年十二月二十二日|二〇二二年十二月二十四日|
| 二〇二二年十二月二十六日|二〇二二年十二月二十七日|
| 二〇二二年十二月二十九日|二〇二二年十二月三十日|
| 二○二二年十二月二日|二〇二二年十二月四日|
| 二〇二二年十二月六日|二〇二二年十二月七日|
| 二〇二二年十二月七日|二〇二二年十二月八日|
| 二〇二二年十二月九日|二〇二二年十二月九日|
| 二〇二二年十二月十三日|二〇二二年十二月十四日|

    • 我需要按原始顺序循环由startDate和endDate组成的键值对。**

我做了什么:

import pandas as pd

data = [
    ("2022-12-15", "2022-12-18"),
    ("2022-12-19", "2022-12-21"),
    ("2022-12-22", "2022-12-24"),
    ("2022-12-26", "2022-12-27"),
    ("2022-12-29", "2022-12-30"),
    ("2022-12-02", "2022-12-04"),
    ("2022-12-06", "2022-12-07"),
    ("2022-12-07", "2022-12-08"),
    ("2022-12-13", "2022-12-14"),
    ("2023-01-01", "2023-01-03"),
]

df = spark.createDataFrame(data).toDF(*('startDate', 'endDate')).toPandas()
dictTest = df.set_index('startDate')['endDate'].to_dict()

print(dictTest)

for k,v in dictTest.items():
    print(f'startDate is {k} and corresponding endDate is {v}.')

上面的代码确实可以将这两列转换为dict,但是dict是无序的,所以我丢失了这两列的原始顺序。
先谢谢你。

nimxete2

nimxete21#

可以使用.to_dictinto参数传入OrderedDict

from collections import OrderedDict 
dictTest = df.set_index('startDate')['endDate'].to_dict(into=OrderedDict)

See the docs here.

58wvjzkj

58wvjzkj2#

只要tableTest是一个 Dataframe ,就可以使用iterrows按原始顺序迭代。

for index, row in tableTest.iterrows():
    startDate = row['startDate']
    endDate = row['endDate']
    print(f'startDate is {startDate} and corresponding endDate is {endDate}.')

相关问题