重新排序字典以适合数据框

时间:2016-01-18 16:35:23

标签: python dictionary pandas

我有import QtQuick 2.0 Item { id: root function startOne() { animOne.start() } function startTwo() { animTwo.start() } property var listEvent: { 1000: root.startOne, 2000: root.startTwo } property int elapsed: 0 property int last_elapsed: 0 Rectangle { id: one x: 0 y: 0 width: 200 height: 200 color: "black" } Rectangle { id: two x: 600 y: 600 width: 200 height: 200 color: "black" } PropertyAnimation { id: animOne target: one properties: "x" to: 600 running: false } PropertyAnimation { id: animTwo target: two properties: "x" to: 0 running: false } function pop(last_elapsed, elapsed) { for (var i = last_elapsed; i <= elapsed; i++) { if (i in root.listEvent) { listEvent[i]() } } } function scheduleEvent(delta) { root.last_elapsed = root.elapsed root.elapsed += delta root.pop(root.last_elapsed, root.elapsed) } Timer { id: scheduler interval: 16 running: true repeat: true onTriggered: { root.scheduleEvent(scheduler.interval) console.log("timer: " + root.elapsed) } } } 这种格式:

dictionary

需要将此数据放在d = {'Name 1': list_of_links,'Name 2': list_of_links,'Name 3': list_of_links} 中,并带有两个DataFrame

columns

我试过这个:

Names and Links
Name 1    -> Link
Name 1    -> Link
...              ...
Name 2    -> Link
Name 2    -> Link
...             ....
Name 3    -> Link
Name 3    -> Link

然后匹配长度

links = []
names = []

for key in d:
    names.append(key)
    links.append(d[key])

最后将所有值复制到两个新列表中,但它似乎不是一个好的方法

2 个答案:

答案 0 :(得分:2)

从两个名称dict和每个links开始:

d = {'Name 1': ['link{}'.format(l) for l in list(range(10))], 'Name 2': ['link{}'.format(l) for l in list(range(10, 20))]}

{'Name 1': ['link0', 'link1', 'link2', 'link3', 'link4', 'link5', 'link6', 'link7', 'link8', 'link9'], 'Name 2': ['link10', 'link11', 'link12', 'link13', 'link14', 'link15', 'link16', 'link17', 'link18', 'link19']}

您可以创建DataFrame .from_dict().stack(),并清理index

df = pd.DataFrame.from_dict(d, orient='index').stack().reset_index(1, drop=True).to_frame().reset_index()
df.columns = ['name', 'link']

得到:

      name    link
0   Name 1   link0
1   Name 1   link1
2   Name 1   link2
3   Name 1   link3
4   Name 1   link4
5   Name 1   link5
6   Name 1   link6
7   Name 1   link7
8   Name 1   link8
9   Name 1   link9
10  Name 2  link10
11  Name 2  link11
12  Name 2  link12
13  Name 2  link13
14  Name 2  link14
15  Name 2  link15
16  Name 2  link16
17  Name 2  link17
18  Name 2  link18
19  Name 2  link19

答案 1 :(得分:1)

在这里,您还可以从元组构建DataFrame:

pd.DataFrame([(i,k)  for i in d.keys() for k in d[i]],columns=['names','links'])