【发布时间】:2020-05-28 17:07:46
【问题描述】:
我有一个数据集如下:
a = pd.DataFrame({'time': pd.date_range(start='2016-03-10', end='2019-03-10'),
'a': [0 for _ in range(1096)],
'b': [0 for _ in range(1096)]})
indices_a = [0,1,3,6,10,15, 20, 40, 50,70, 100,400,700]
indices_b = [0,1,3,6,10,15, 20, 40, 50,70, 100,400,700]
a.loc[indices_a,'a'] = 1
a.loc[indices_b,'b'] = 1
上面将创建一个数据框,其中 a 和 b 的一些索引分别为 0 和 1。
我想要做的是使用 pandas 库函数来循环每一列并查找值是否为 1,然后创建另一个数据框,如下例所示
下面的日期只是一个示例,它表示值为 1 和类别作为列名的索引。所以下面是不正确的,只是为了让我了解一下我的输入
time | category
2018-03-10 | a
2018-02-10 | a
2018-04-10 | a
2018-05-10 | a
2018-06-10 | b
2018-07-10 | b
2018-08-10 | b
2018-09-10 | b
2018-10-10 | b
我的尝试:
output = pd.DataFrame()
for col in a.columns[1:]:
temp = pd.DataFrame({'category': [col for _ in range(len(a[a[col]==1]))],
'time':a[a[col]==1]['time'].values})
output = output.append(temp, ignore_index=True)
# Although my attemp produced correct output but its just not the dataframe or pandas way of doing things. Since I wish to know more pandas way of handling the dataframe, please kindly use the pandas functions.
【问题讨论】: