Python 不匹配的列名联接
我有一些时间序列健康数据的表,如: 我想得到每家医院每种体型每次的这两个指标的商,如下所示:Python 不匹配的列名联接,python,pandas,dataframe,Python,Pandas,Dataframe,我有一些时间序列健康数据的表,如: 我想得到每家医院每种体型每次的这两个指标的商,如下所示: 如何在数据帧中实现这一点?如果您提供了数据预透视示例,则可以获得更好的解决方案 hr = df.heart_rate bp = df.blood_pressure keys = ['heart_rate', 'blood_pressure', 'my_metric'] pd.concat([hr, bp, hr / bp], axis=1, keys=keys) 示例 idx = pd.Mul
如何在数据帧中实现这一点?如果您提供了数据预透视示例,则可以获得更好的解决方案
hr = df.heart_rate
bp = df.blood_pressure
keys = ['heart_rate', 'blood_pressure', 'my_metric']
pd.concat([hr, bp, hr / bp], axis=1, keys=keys)
示例
idx = pd.MultiIndex.from_product([
['t%s'%i for i in range(1, 6)],
['h1', 'h2']
], names=['Time', 'Hospital'])
col = pd.MultiIndex.from_product([
['heart_rate', 'blood_pressure'],
['Type1', 'Type2']
], names=['metric', 'bodytype'])
df = pd.DataFrame(
np.random.randint(10, size=(10, 4)),
idx, col
)
df
metric heart_rate blood_pressure
bodytype Type1 Type2 Type1 Type2
Time Hospital
t1 h1 6 3 8 3
h2 3 4 2 9
t2 h1 5 7 7 0
h2 9 4 9 4
t3 h1 8 8 7 9
h2 5 5 3 5
t4 h1 0 1 5 1
h2 4 9 5 9
t5 h1 0 0 1 5
h2 2 0 5 0
如果您提供了数据透视前的示例,则可以获得更好的解决方案
hr = df.heart_rate
bp = df.blood_pressure
keys = ['heart_rate', 'blood_pressure', 'my_metric']
pd.concat([hr, bp, hr / bp], axis=1, keys=keys)
示例
idx = pd.MultiIndex.from_product([
['t%s'%i for i in range(1, 6)],
['h1', 'h2']
], names=['Time', 'Hospital'])
col = pd.MultiIndex.from_product([
['heart_rate', 'blood_pressure'],
['Type1', 'Type2']
], names=['metric', 'bodytype'])
df = pd.DataFrame(
np.random.randint(10, size=(10, 4)),
idx, col
)
df
metric heart_rate blood_pressure
bodytype Type1 Type2 Type1 Type2
Time Hospital
t1 h1 6 3 8 3
h2 3 4 2 9
t2 h1 5 7 7 0
h2 9 4 9 4
t3 h1 8 8 7 9
h2 5 5 3 5
t4 h1 0 1 5 1
h2 4 9 5 9
t5 h1 0 0 1 5
h2 2 0 5 0
我通过创建一个不同的pivot_表,将
bodytype
从columns
移动到index
来解决这个问题,然后简单地划分
pivot\u-df[“我的度量”]=pivot\u-df[“心率”]/pivot\u-df[“血压”]
我通过创建不同的pivot\u表,然后简单地划分,将体型从列移动到索引,解决了这个问题
pivot\u-df[“我的度量”]=pivot\u-df[“心率”]/pivot\u-df[“血压”]
你没有真正回答你自己的问题。您提供了不同的格式,因为这样做更容易。首先,您可以通过pivot\u df.unstack('bodytype')
完成这项工作。其次,我要说的是,在没有提供生成透视表所需的数据的情况下提出问题,然后根据您没有提供的数据提供解决方案,这是一种糟糕的形式。这对其他人有什么帮助?你没有真正回答自己的问题。您提供了不同的格式,因为这样做更容易。首先,您可以通过pivot\u df.unstack('bodytype')
完成这项工作。其次,我要说的是,在没有提供生成透视表所需的数据的情况下提出问题,然后根据您没有提供的数据提供解决方案,这是一种糟糕的形式。这对其他人有什么帮助?