0

我有要在几个不同时间段内评估的车辆信息,并且在浏览信息时正在修改 DataFrame 中的不同列。我正在处理当前和以前的时间段,因此我需要将两者结合起来并一起处理它们。

我遇到的问题是,当我使用“时间”列作为 pandas 中的索引并循环遍历数据时,返回的对象是 DataFrame 或 Series,具体取决于时间段内的车辆(或行)数. 当我尝试在 Series 对象上使用 DataFrame 方法时,对象类型的这种更改会产生错误。

我创建了一个小示例程序,显示了我正在尝试做的事情以及我收到的错误。请注意,这是一个示例,而不是真正的代码。我尝试过简单地按时间段查询数据,而不是使用索引,这很有效,但对于我需要做的事情来说太慢了。

import pandas as pd

df = pd.DataFrame({
    'id' : range(44, 51),
    'time' : [99,99,97,97,96,96,100],
    'spd' : [13,22,32,41,42,53,34],
})


df = df.set_index(['time'], drop = False)

st = True

for ind in df.index.unique():

    data = df.ix[ind]

    print data

    if st:
        old_data = data
        st = False
    else:
        c = pd.concat([data, old_data])

    #do some work here

输出是:

  id  spd  time
time               
99    44   13    99
99    45   22    99
      id  spd  time
time               
97    46   32    97
97    47   41    97
      id  spd  time
time               
96    48   42    96
96    49   53    96
id       50
spd      34
time    100
Name: 100, dtype: int64
Traceback (most recent call last):
  File "C:/Users/m28050/Documents/Projects/fhwa/tca/v_2/code/pandas_ind.py", line 24, in <module>
    c = pd.concat([data, old_data])
  File "C:\Python27\lib\site-packages\pandas\tools\merge.py", line 873, in concat
    return op.get_result()
  File "C:\Python27\lib\site-packages\pandas\tools\merge.py", line 946, in get_result
    new_data = com._concat_compat([x.values for x in self.objs])
  File "C:\Python27\lib\site-packages\pandas\core\common.py", line 1737, in _concat_compat
    return np.concatenate(to_concat, axis=axis)
ValueError: all the input arrays must have same number of dimensions

如果有人有正确的方法来循环遍历 DataFrame 并更新列,或者可以指出要使用的不同方法,那就太好了。

谢谢你的帮助。

吉姆

4

1 回答 1

0

我认为groupby可以在这里提供帮助:

In [11]: spd_lt_40 = df1[df1.spd < 40]

In [12]: spd_lt_40_count = spd_lt_40.groupby('time')['id'].count()

In [13]: spd_lt_40_count
Out[13]:
time
97      1
99      2
100     1
dtype: int64

然后将其设置为原始 DataFrame 中的一列:

In [14]: df1['spd_lt_40_count'] = spd_lt_40_count

In [15]: df1['spd_lt_40_count'].fillna(0, inplace=True)

In [16]: df1
Out[16]:
      id  spd  time  spd_lt_40_count
time
99    44   13    99                2
99    45   22    99                2
97    46   32    97                1
97    47   41    97                1
96    48   42    96                0
96    49   53    96                0
100   50   34   100                1
于 2013-07-08T12:34:14.630 回答