按时间单位而不是按行迭代数据帧

2024-04-18 14:05:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas.DataFrame看起来是这样的:

Time(minutes)    column2       column1
420              1             5
420              2             10
420              3             8
421              1             4
421              2             9
421              3             7

我知道如何使用iterrows()逐行迭代,但是有没有一种有效的方法可以按列(time)中的时间单位进行迭代,以便在每次迭代中处理给定时间的数据?比如:

time = 420
while(time <= max_time):
   temp <- fetch the sub-dataframe for given time
   process(temp)
   update original df with temp #guaranteed it won't affect any other rows other than the current set of rows
   time += 1

Tags: the方法dataframepandastime时间单位temp
2条回答

可以使用^{}按时间而不是按行进行迭代,如:

代码:

for grp in df.groupby('Time(minutes)'):
    ...

测试代码:

df = pd.read_fwf(StringIO(u"""
    Time(minutes)    column2       column1
    420              1             5
    420              2             10
    420              3             8
    421              1             4
    421              2             9
    421              3             7"""), header=1)

print(df)
for grp in df.groupby('Time(minutes)'):
    print(grp)

结果:

   Time(minutes)  column2  column1
0            420        1        5
1            420        2       10
2            420        3        8
3            421        1        4
4            421        2        9
5            421        3        7

(420,    Time(minutes)  column2  column1
0            420        1        5
1            420        2       10
2            420        3        8)
(421,    Time(minutes)  column2  column1
3            421        1        4
4            421        2        9
5            421        3        7)

有两条路要走。第一种基本上保持迭代格式的方法是手动对数据帧进行子集划分:

for time in df['time_minutes'].unique():
    temp = df.loc[df['time_minutes'] == time] 
    process(temp)
    # or alternatively, make your changes directly on temp (depending what they are),
    # for example, something like this:
    # df.loc[df['time_minutes'] == time, 'some_column_name'] = assign_something_here

另一种可能更有效的方法是使用上面由Stephen Rauch建议的groupby

相关问题 更多 >