【发布时间】:2020-03-25 02:09:07
【问题描述】:
【问题讨论】:
-
您能否从样本数据中添加预期输出,也是 3 行?您是否需要在新 Dataframe 中重复上一列中的
RESP值?
标签: python pandas pandas-groupby data-science google-colaboratory
【问题讨论】:
RESP 值?
标签: python pandas pandas-groupby data-science google-colaboratory
一种可能的解决方案是使用reshape,列长度的唯一必要模数是0(因此可以将所有数据转换为4列DataFrame):
df1 = pd.Dataframe(df.values.reshape(-1, 4), columns=['RESP','HR','SPO2','PULSE'])
df1['RESP1'] = df['RESP'].shift(-1)
通用数据解决方案:
a = '46 122 0 0 46 122 0 0 45 122 0 0 45 122 0'.split()
df = pd.DataFrame([a]).astype(int)
print (df)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 46 122 0 0 46 122 0 0 45 122 0 0 45 122 0
#flatten values
a = df.values.ravel()
#number of new columns
N = 4
#array filled by NaNs for possible add NaNs to end of last row
arr = np.full(((len(a) - 1)//N + 1)*N, np.nan)
#fill array by flatten values
arr[:len(a)] = a
#reshape to new DataFrame (last value is NaN)
df1 = pd.DataFrame(arr.reshape((-1, N)), columns=['RESP','HR','SPO2','PULSE'])
#new column with shifting first col
df1['RESP1'] = df1['RESP'].shift(-1)
print(df1)
RESP HR SPO2 PULSE RESP1
0 46.0 122.0 0.0 0.0 46.0
1 46.0 122.0 0.0 0.0 45.0
2 45.0 122.0 0.0 0.0 45.0
3 45.0 122.0 0.0 NaN NaN
【讨论】:
2348 % 5 = 3 则意味着必须删除最后 3 个值才能正常工作。或者需要添加缺失值以像最后一行一样结束 data, data, data, NaN, NaN?
这是groupby的另一种方式:
df = pd.DataFrame(np.random.arange(12), columns=list('abcd'*3))
new_df = pd.concat((x.stack().reset_index(drop=True)
.rename(k) for k,x in df.groupby(df.columns, axis=1)),
axis=1)
new_df = (new_df.assign(a1=lambda x: x['a'].shift(-1))
.rename(columns={'a1':'a'})
)
输出:
a b c d a
0 0 1 2 3 4.0
1 4 5 6 7 8.0
2 8 9 10 11 NaN
【讨论】:
a 列 - 而不是,因为选择问题