3

I wrote this ugly piece of code. It does the job, but it is not elegant. Any suggestion to improve it?

Function returns a dict given i, j.

pairs = [dict({"i":i, "j":j}.items() + function(i, j).items()) for i,j in my_iterator]
pairs = pd.DataFrame(pairs).set_index(['i', 'j'])

The dict({}.items() + function(i, j).items()) is supposed to merge both dict in one as dict().update() does not return the merged dict.

4

1 回答 1

4

一个最喜欢的技巧*返回一个更新的新创建的字典:

dict(i=i, j=j, **function(i, j))

*以及关于这是否真的“有效”的很多争论......

或许还值得一提的是 DataFramefrom_records方法:

In [11]: my_iterator = [(1, 2), (3, 4)]

In [12]: df = pd.DataFrame.from_records(my_iterator, columns=['i', 'j'])

In [13]: df
Out[13]:
   i  j
0  1  2
1  3  4

我怀疑通过矢量化你的函数会有一种更有效的方法(但如果没有更具体的情况,很难说什么更有意义)......

于 2013-07-12T18:18:36.763 回答