python - 拆分列名并从列名中的数据创建新列
问题描述
我在熊猫数据框中有传感器数据,如下所示:
Timestamp 1014.temperature 1014.humidity 1015.temperature 1015.humidity 1016.temperature 1016.humidity
2017-10-01 00:00:00 11.396667 92.440806 10.513333 92.204295 11.040000 92.959605
由每列中点之前的SensorID
4 位数字给出。Timestamp
索引数据。数据继续用于多个时间戳和 SensorID。
我可以做些什么来检索SensorID
每列中的 以创建一个新列,以便我的数据框看起来像:
Timestamp SensorID Temperature Humidity
2017-10-01 00:00:00 1014 11.396667 92.440806
2017-10-01 00:00:00 1015 10.513333 92.204295
2017-10-01 00:00:00 1016 11.040000 92.959605
谢谢。
解决方案
首先str.split
是MultiIndex
在列中,并通过DataFrame.stack
第一级进行整形,最后DataFrame.reset_index
是rename
:
#if Timestamp is column
#df = df.set_index('Timestamp')
df.columns = df.columns.str.split('.', expand=True)
df = df.stack(level=0).reset_index().rename(columns={'level_1':'SensorID'})
print (df)
Timestamp SensorID humidity temperature
0 2017-10-01 00:00:00 1014 92.440806 11.396667
1 2017-10-01 00:00:00 1015 92.204295 10.513333
2 2017-10-01 00:00:00 1016 92.959605 11.040000
推荐阅读
- python - CoolProp Python 中的 REFPROP 库
- angular - 合并来自两个 Angular 项目的 Karma 测试结果
- sql - 使用 SQL 将具有列名称的行转置为列
- java - 如何用google cloud dataflow和java依次生成gcs文件?
- reactjs - 承诺后如何使用react-router重定向到另一个url?
- php - PHP 性能包装 if 语句
- python - Python程序挂起,不知道为什么
- python - 使用 pydantic 生成动态模型
- aspose-cells - 获取 com.aspose.cells.CellsException:无效的 Excel2007Xlsx 文件格式
- r - R中多边形和线的复杂裁剪(空间交点?)