python - 如何根据Python中的时间戳索引将行转置为单列?

标签 python pandas ipython

示例输入数据集是:

0 2017-11-17 10:23:28.691 788 756 789 780

1 2017-11-17 10:23:29.731 788 783 0 0

2 2017-11-17 10:23:30.655 747 0 0 0

3 2017-11-17 10:23:31.627 766 0 0 0

4 2017-11-17 10:23:32.606 807 0 0 0

我想要的示例输出数据集:

0 2017-11-17 10:23:28.691 788

0 2017-11-17 10:23:28.691 756

0 2017-11-17 10:23:28.691 789

0 2017-11-17 10:23:28.691 780

1 2017-11-17 10:23:29.731 788

1 2017-11-17 10:23:29.731 783

2 2017-11-17 10:23:30.655 747

3 2017-11-17 10:23:31.627 766

4 2017-11-17 10:23:32.606 807

如何通过 python 或 pandas 做到这一点?或者还有其他技术可以做到这一点吗?

最佳答案

使用set_index + stack ,然后过滤出 0 行,最后从 Series 创建 DataFrame:

print (df)
                      date    a    b    c    d
0  2017-11-17 10:23:28.691  788  756  789  780
1  2017-11-17 10:23:29.731  788  783    0    0
2  2017-11-17 10:23:30.655  747    0    0    0
3  2017-11-17 10:23:31.627  766    0    0    0
4  2017-11-17 10:23:32.606  807    0    0    0

a = df.set_index('date').stack()
df = a[a != 0].reset_index(drop=True, level=1).reset_index(name='a')
print (df)
                      date    a
0  2017-11-17 10:23:28.691  788
1  2017-11-17 10:23:28.691  756
2  2017-11-17 10:23:28.691  789
3  2017-11-17 10:23:28.691  780
4  2017-11-17 10:23:29.731  788
5  2017-11-17 10:23:29.731  783
6  2017-11-17 10:23:30.655  747
7  2017-11-17 10:23:31.627  766
8  2017-11-17 10:23:32.606  807

关于python - 如何根据Python中的时间戳索引将行转置为单列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47437966/

相关文章:

python - 在 jupyter/ipython notebook 中设置优先级/niceness

python - 删除单元格 ipython 2.0

python - 我如何从字符串中获取python函数对象

python - Selenium 函数中的引用变量

python - 如何在python中将数组转换为字典

python - 用 Pandas : Is there an equivalent to dplyr's select(. ..,一切())重新排列列?

python - 如何使 FunctionTransformer 在 DataFrameMapper 中工作

python - 在 Python 中使用 ix 对 DataFrame 进行子集化

python - 如何更改 iPython 的内核/python 版本?

python - Dict 会以相同的顺序返回键和值吗?