【发布时间】:2020-06-28 19:31:24
【问题描述】:
我想过滤数据框以在嵌套 for 循环中获取子数据集,然后将 some_function 应用于每个子数据集,根据名为 @987654323 的持续时间列从每个子数据集中选择一行@,然后将所有单独的行连接到一个数据帧中。
代码如下:
def tm(df):
total_t = []
df['YearMonth'] = df['Timestamp'].apply(lambda x: x.strftime('%Y-%m'))
for yearmonth in df['YearMonth'].unique():
for id in df['Id'].unique():
sub_df = df[(df['YearMonth'] == yearmonth) &(df['Id'] == id)]
res_df = some_function(sub_df)
res_df['TimeDiff'] = res_df['EndTime'] - res_df['StartTime']
res_df = res_df.loc[(res_df['TimeDiff']> datetime.timedelta(seconds=60)) & (res_df['TimeDiff']<datetime.timedelta(minutes=5))]
long_event = res_df.loc[res_df['TimeDiff'] ==res_df['TimeDiff'].max()]
total_t.append(pd.Series(long_event))
# total_t.append(pd.Series(long_event))
total_t = pd.concat([total_t])
return total_t
tm(dfx)
res_df 是一个数据框,如下所示:
Id Date StartTime EndTime StartVal EndVal TimeDiff
0 89 2012-03-10 2012-03-10 00:00:08.483 2012-03-10 00:00:11.607 41.5 41.0 00:00:03.124000
1 181 2012-03-10 2012-03-10 00:02:49.687 2012-03-10 00:02:52.813 41.5 41.0 00:00:03.126000
我想在每个子数据集中选择TimeDiff 最长的行,以及60seconds 到5minutes 范围内的行,将它们组合成一个数据框。
但是它发现了错误:
TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame"
我意识到这可能是因为作为参数传递的数据帧应该是基于this question 的list 形式。我试过了
total_t = pd.concat([total_t])
# Original code :total_t = pd.concat(total_t)
返回:
TypeError: cannot concatenate object of type '<class 'list'>'; only Series and DataFrame objs are valid
预期输出,仍然是这种格式,但行数更多:
Id Date StartTime EndTime StartVal EndVal TimeDiff
0 89 2012-03-10 2012-03-10 00:00:08.483 2012-03-10 00:00:11.607 41.5 41.0 00:00:03.124000
1 181 2012-03-10 2012-03-10 00:02:49.687 2012-03-10 00:02:52.813 41.5 41.0 00:00:03.126000
...
更新:
试过了:
total_t.append(long_event)
total_t = pd.Series(total_t)
# total_t = pd.DataFrame(pd.concat([total_t]))
total_t = pd.concat([total_t])
只返回一行:
0 Id Date StartTime EndTime StartVal
EndVal TimeDiff
37 235 2012-03-10 2012-03-10 19:43:32.260 2012-03-10 19:48:06.270 42.0
41.5 00:04:34.010000
dtype: object
【问题讨论】:
标签: python pandas dataframe for-loop nested