【发布时间】:2019-08-28 13:12:34
【问题描述】:
我正在尝试简化对以下数据框的一些数据评估:
3 9
measurement_location voltage
NaN NaN Gleichrichtung ... Gegenrichtung
NaN > 50mm ... 1mm < x < 5mm
B-Säule 9,5 V 52 ... 41
13 V 47 ... 55
15,5 V 61 ... 65
Scheibenmitte 9,5 V 49 ... 60
13 V 60 ... 57
15,5 V 69 ... 66
A-Säule 9,5 V 46 ... 49
13 V 50 ... 48
15,5 V 58 ... 58
数据框已从 Excel 工作表中读取,该工作表包含一个表,该表在前两列和前两行具有索引。实际上它是一个二维 MultiIndex 数据框。 实际数据从第 3 行第 3 列开始。
前两列中的measurement_location 和voltage 是索引。
在前两行中有基于列的索引的值。我想将表转换为一个平面值列表 - 包括基于第 1 行和第 2 行值的新索引。
目标:
measurement_location voltage direction distance value
B-Säule 9,5 V Gleichrichtung > 50mm 52 # col "3", 1st data row
Gegenrichtung 1mm < x < 5mm 41 # col "9", 1st data row
...
Scheibenmitte 9,5 V Gleichrichtung > 50mm 49 # column "3", 4th data row
Gegenrichtung 1mm < x < 5mm 60 # column "9", 4th data row
...
所以这意味着它想从
的 values 创建新的索引- 第 0 行称之为“方向”
- 第 1 行称之为“距离”。
我想为一行添加一个新索引,但我找不到方法,如何将它添加回 MultiIndex...
# get line of measurements
measurements = idf.iloc[2]
# get new "index" by values of each values column information
column_values = idf.iloc[0]
pd.DataFrame(measurements).set_index(column_values).unstack()
# yields:
(nan, nan)
B-Säule 9,5 V Gleichrichtung 52
Gleichrichtung 53
Gleichrichtung 54
Gleichrichtung 50
Gleichrichtung 55
Gleichrichtung 56
Gegenrichtung 41
Gegenrichtung 42
Gegenrichtung 43
dtype: object
更新:使用一些数据的一些最小示例:
idx = pd.MultiIndex.from_product([
['A', 'B', 'C'],
['9', '13', '16']
],
names=['measurement_location', 'voltage']
)
data = np.arange(36).reshape(9, 4)
df = pd.DataFrame(data, idx)
0 1 2 3
measurement_location voltage
A 9 0 1 2 3
13 4 5 6 7
16 8 9 10 11
B 9 12 13 14 15
13 16 17 18 19
16 20 21 22 23
C 9 24 25 26 27
13 28 29 30 31
16 32 33 34 35
在这个最小示例中,每列的值共享相同的索引元组(就像上面的真实数据中的“3”列:(Gleichrichtung,> 50mm))。
因此,对于每个值,我需要提取其列的索引元组并将其分配回现有的 MultiIndex。
就像 target 中描述的那样,最后我希望每个值有一行
measurement_location voltage direction distance value
B-Säule 9,5 V Gleichrichtung > 50mm 52
我想避免 for 循环并使用 pandas 方法。
【问题讨论】:
-
您能否以更易于重现的格式发布示例数据?在所有空格字符和
...截断之间,很难重现输入数据。 -
是
Gleichrichtung&Gegenrichtung第一个数据集中列的名称吗?如果是这样,这意味着measurement_location&voltage是索引? -
Gleichrichtung&Gegenrichtung是我想用来创建新索引级别的两个(分类)值。measurement_location&voltage是索引(MultiIndex) -
@PeterLeimbigler:我添加了一些最小的示例数据(由于我缺乏 pandas 知识,我不知道如何使用包含 NaN 索引值的另外两行来重现原始结构)
标签: python pandas multi-index