python - 在列表中搜索数据并将它们导出到 .csv 文件中

标签 python algorithm

我已经完成了另一部分代码并得到了两组数字:

set1(西澳大利亚的邮政编码和租金):

[['6004', '240'], ['6004', '350'], ['6004', '350'], ['6004', '315'], ['6004', '490'], ['6004', '280'], ['6004', '275'], ['6004', '240'], ['6050', '260'], ['6050', '330'], ['6050', '220'], ['6050', '250'], ['6000', '390'], ['6000', '220'], ['6000', '400'], ['6000', '250'], ['6000', '320'], ['6000', '390'], ['6000', '220'], ['6000', '400'], ['6004', '395'], ['6004', '230'], ['6004', '350'], ['6004', '300'], ['6004', '300'], ['6004', '340'], ['6000', '420'], ['6000', '190'], ['6000', '300'], ['6000', '380'], ['6000', '270'], ['6000', '380'], ['6000', '350'], ['6000', '380'], ['6004', '360'], ['6004', '450'], ['6004', '200'], ['6004', '250'], ['6004', '350']]

set2(set1 中的邮政编码):

['6004', '6050', '6000']

我现在需要做的是像这样将它们放入 .csv 文件中:

enter image description here

邮政编码位于第一行(如索引)。其余行是这些邮政编码的租金(例如:在邮政编码 6004 中,有 3 栋房子,租金为 240,350,350)

我应该用什么样的方法来得到我想要的东西?

我试过字典,但它说只需要 2 个元素。

最佳答案

给定:

postcodes_rent=[['6004', '240'], ['6004', '350'],.......]
postcodes=['6004', '6050', '6000']

创建字典:

postcodes_rent_dict={p:[pr[1] for pr in postcodes_rent if pr[0]==p] for p in postcodes}
{'6004': ['240', '350', '350'.....], 
 '6050': ['260', '330', '220'.....], 
 '6000': ['390', '220', '400'.....]}

将其转换为数据框(以邮政编码作为列名):

import pandas as pd
df=pd.DataFrame.from_dict(postcodes_rent_dict,orient='index').transpose()

写入csv文件

df.to_csv("test.csv")

关于python - 在列表中搜索数据并将它们导出到 .csv 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51918128/

相关文章:

algorithm - barnes hut 树在 insert 和 internalInsert 之间无限循环

javascript - 按键组合json数组,javascript

python - 使用复数遍历二维数组中的邻居

python - 从 TensorFlow 图中提取权重以在 Keras 中使用它们

python - 如何查找破坏日期时间索引连续性的缺失日期或小时?

python - 映射数组中满足条件的位置

Java:Map中的内部数据结构

python - 从文本文件创建术语文档矩阵

python - python多处理中的共享变量

algorithm - 哈希查找和二分查找哪个更快?