本文介绍了 pandas :有效拆分条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫dataframe,其列如下:

I have a Pandas dataframe with columns as such:

event_id,obj_0_type,obj_0_foo,obj_0_bar,obj_1_type,obj_1_foo,obj_1_bar,obj_n_type,obj_n_foo,obj_n_bar,....

event_id, obj_0_type, obj_0_foo, obj_0_bar, obj_1_type, obj_1_foo, obj_1_bar, obj_n_type, obj_n_foo, obj_n_bar, ....

例如:

col_idx = ['event_id']
[col_idx.extend(('obj_%d_id' %d, 'obj_%d_foo' %d, 'obj_%d_bar' %d)) for d in range(5)]
event_id = np.array(range(0,5))
data = np.random.rand(15,5)
data = np.vstack((event_id, data))
df = DataFrame(data.T, index = range(5), columns = col_idx)

我想拆分数据帧的每一行,以便每个对象只有一个条目,例如:

I would like to split each individual row of the dataframe so that I'd have a single entry per object, as such:

event_id,obj_type,obj_foo,obj_bar

event_id, obj_type, obj_foo, obj_bar

在给定事件的所有对象之间共享event_id的地方.

Where event_id would be shared among all the objects of a given event.

有很多非常慢的方法(遍历数据框的行并创建新的序列对象),但是这些方法非常慢,而且显然是非Python的.有没有一种更简单的方式让我失踪?

There are lots of very slow ways of doing it (iterating over the dataframe rows and creating new series objects) but those are atrociously slow and obviously unpythonic. Is there a simpler way I am missing?

推荐答案

在freenode上#pydata中一些人的建议下,这是我想出的:

With some suggestions from some people in #pydata on freenode, this is what I came up with:

data = []
for d in range(5):
    temp = df.ix[:, ['event_id', 'obj_%d_id' % d, 'obj_%d_foo' % d, 'obj_%d_bar' % d]]
    temp.columns = ['event_id', 'obj_id', 'obj_foo', 'obj_bar']
    # Giving columns unique names.
    temp.index = temp['event_id']*10 + d
    # Creating a unique index.
    data.append(temp)

concat(data)

这有效并且相当快!

这篇关于 pandas :有效拆分条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 03:07