【发布时间】:2019-02-09 00:07:00
【问题描述】:
我想将 df 的“位置”列分组以保留在 new_df 中,并使用 Python 2.7 按“日期时间”列进行排序
这是我的 df:
>>df
DateTime Product Location Value
0 12-07-2018 A S1 1.313
1 12-07-2018 A S2 3.089
2 12-07-2018 A S3 1.890
3 12-07-2018 A S4 3.136
4 12-07-2018 B S1 3.258
5 13-07-2018 B S2 3.113
6 13-07-2018 B S3 2.651
7 13-07-2018 B S4 2.135
8 13-07-2018 C S1 1.555
9 14-07-2018 C S2 2.009
10 14-07-2018 C S3 1.757
11 14-07-2018 D S1 1.808
12 14-07-2018 D S2 1.511
13 15-07-2018 D S3 2.265
14 15-07-2018 D S4 2.356
15 15-07-2018 D S5 2.950
16 15-07-2018 E S1 3.300
17 16-07-2018 E S2 3.110
18 16-07-2018 F S1 2.068
我想在“位置”列中分隔 S1、S2、S3、S4、...(等)并按日期时间排序
这是我需要的结果:
>>new_df_S1
DateTime Product Location Value
0 12-07-2018 A S1 1.313
1 12-07-2018 B S1 3.258
2 13-07-2018 C S1 1.555
3 14-07-2018 D S1 1.808
4 15-07-2018 E S1 3.300
5 16-07-2018 F S1 2.068
>>new_df_S2
DateTime Product Location Value
0 12-07-2018 A S2 3.089
1 13-07-2018 B S2 3.113
2 14-07-2018 C S2 2.009
3 14-07-2018 D S2 1.511
4 16-07-2018 E S2 3.110
and another (new_df_S3, new_df_S4, new_df_S5, ...)
现在我将这段代码用于我的结果但是我的数据框有 1000 行或更多。它使用很多时间搜索 S1, S2, ... 并保持到 new_df :
> for r in range(len(df)) :
if df.iloc[r,2] == "S1":
new_df_S1.loc[len(new_df_S1)] = [ df.iloc[r, 0], df.iloc[r, 1],
df.iloc[r, 2], df.iloc[r, 3] ]
elif df.iloc[r,2] == "S2":
new_df_S2.loc[len(new_df_S2)] = [ df.iloc[r, 0], df.iloc[r, 1],
df.iloc[r, 2], df.iloc[r, 3] ]
elif df.iloc[r,2] == "S3":
new_df_S3.loc[len(new_df_S3)] = [ df.iloc[r, 0], df.iloc[r, 1],
df.iloc[r, 2], df.iloc[r, 3] ]
elif df.iloc[r,2] == "S4":
new_df_S4.loc[len(new_df_S4)] = [ df.iloc[r, 0], df.iloc[r, 1],
df.iloc[r, 2], df.iloc[r, 3] ]
.
.
.
and another (new_df_S5, new_df_S6, ...)
有没有办法减少单独 S1、S2、S3、...的时间?
【问题讨论】:
标签: python-2.7 pandas dataframe pandas-groupby