向下移动列并复制pandas中的键

2024-05-15 22:54:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

ID first mes1.1 mes 1.2 ... mes 1.10 mes2.[1-10] mes3.[1-10] 123df John 5.5 130 45 [12,312,...] [123,346,53] ...

其中,我使用[]表示法对列进行了缩写。所以在这个数据帧中我有31列:firstmes1.[1-10]mes2.[1-10]mes3.[1-10]。每一行都有一个唯一的索引:ID。你知道吗

我想建立一个新表,在其中复制所有列值(这里用IDfirst表示),并将mes2mes3列(其中20列)“向下”移动,得到如下结果:

ID first mes1 mes2 ... mes10 123df John 5.5 130 45 123df John 341 543 53 123df John 123 560 567 ...


Tags: 数据idjohnfirst表示法mes列值mes1
1条回答
网友
1楼 · 发布于 2024-05-15 22:54:49
# How I set up your dataframe (please include a reproducible df next time)
df = pd.DataFrame(np.random.rand(6,31), index=["ID" + str(i) for i in range(6)], 
columns=['first'] + ['mes{0}.{1}'.format(i, j) for i in range(1,4) for j in range(1,11)])
df['first'] = 'john'

那么有两种方法可以做到这一点

# Generate new underlying array
first = np.repeat(df['first'].values, 3)[:, np.newaxis]
new_vals = df.values[:, 1:].reshape(18,10)
new_vals = np.hstack((first, new_vals))
# Create new df
m = pd.MultiIndex.from_product((df.index, range(1,4)), names=['ID', 'MesNum'])
pd.DataFrame(new_vals, index=m, columns=['first'] + list(range(1,11)))

或者只使用熊猫

df.columns = ['first'] + list(range(1,11))*3
pieces = [df.iloc[:, i:i+10] for i in range(1,31, 10)]
df2 = pd.concat(pieces, keys = ['first', 'second', 'third'])
df2 = df2.swaplevel(1,0).sortlevel(0)
df2.insert(0, 'first', df['first'].repeat(3).values)

相关问题 更多 >