按元素分组
Group by an element
所以我在 Python 上有一个数据框,它有很多变量同时发生并同时被取消,我想把它们变成一个按时间分组的新数据框,例如它喜欢:
Value
ID
Unit
Key
Date
10
10
m/s^2
Acceleration
01/01/2000 12:00:01
On
11
String
Machine
01/01/2000 12:00:01
2.0
12
bar
Pressure
01/01/2000 12:00:01
12
13
m/s^2
Acceleration
01/01/2000 12:00:02
Off
14
String
Machine
01/01/2000 12:00:02
1.5
15
bar
Pressure
01/01/2000 12:00:02
但我想将其设置为:
Date
Acceleration
Pressure
Lid
01/01/2000 12:00:01
10 m/s^2
2.0 bar
On
01/01/2000 12:00:02
12 m/s^2
1.5 bar
Off
我可以 link 将这些值组合在一起,但我该如何在多行中进行这样的分组?
IIUC,你需要修改你的专栏,然后 pivot
:
# merge value/unit except for "Machine"
df['value'] = np.where(df['Key'].eq('Machine'),
df['Value'],
df['Value'].astype(str)+' '+df['Unit'])
# replace "Machine" with "Lid"
df['col'] = df['Key'].replace({'Machine': 'Lid'})
# pivot using the new columns
df2 = (df
.pivot(index='Date', columns='col', values='value')
.rename_axis(columns=None).reset_index()
)
输出:
Date Acceleration Lid Pressure
0 01/01/2000 12:00:01 10 m/s^2 On 2.0 bar
1 01/01/2000 12:00:02 12 m/s^2 Off 1.5 bar
所以我在 Python 上有一个数据框,它有很多变量同时发生并同时被取消,我想把它们变成一个按时间分组的新数据框,例如它喜欢:
Value | ID | Unit | Key | Date |
---|---|---|---|---|
10 | 10 | m/s^2 | Acceleration | 01/01/2000 12:00:01 |
On | 11 | String | Machine | 01/01/2000 12:00:01 |
2.0 | 12 | bar | Pressure | 01/01/2000 12:00:01 |
12 | 13 | m/s^2 | Acceleration | 01/01/2000 12:00:02 |
Off | 14 | String | Machine | 01/01/2000 12:00:02 |
1.5 | 15 | bar | Pressure | 01/01/2000 12:00:02 |
但我想将其设置为:
Date | Acceleration | Pressure | Lid |
---|---|---|---|
01/01/2000 12:00:01 | 10 m/s^2 | 2.0 bar | On |
01/01/2000 12:00:02 | 12 m/s^2 | 1.5 bar | Off |
我可以 link 将这些值组合在一起,但我该如何在多行中进行这样的分组?
IIUC,你需要修改你的专栏,然后 pivot
:
# merge value/unit except for "Machine"
df['value'] = np.where(df['Key'].eq('Machine'),
df['Value'],
df['Value'].astype(str)+' '+df['Unit'])
# replace "Machine" with "Lid"
df['col'] = df['Key'].replace({'Machine': 'Lid'})
# pivot using the new columns
df2 = (df
.pivot(index='Date', columns='col', values='value')
.rename_axis(columns=None).reset_index()
)
输出:
Date Acceleration Lid Pressure
0 01/01/2000 12:00:01 10 m/s^2 On 2.0 bar
1 01/01/2000 12:00:02 12 m/s^2 Off 1.5 bar