我有以下数据:
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] ...
其中有使用[]
符号的缩写列。因此,在这个dataframe中,我有31列:first
、mes1.[1-10]
、mes2.[1-10]
和mes3.[1-10]
。每一行都由一个唯一的索引:ID
键决定。
我想要形成一个新的表,其中我复制了所有的列值(在这里由ID
和first
表示),并将mes2
和mes3
列(其中20列)“向下”移动,如下所示:
ID first mes1 mes2 ... mes10 123df John 5.5 130 45 123df John 341 543 53 123df John 123 560 567 ...
发布于 2015-01-30 20:34:35
# 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)
https://stackoverflow.com/questions/28242471
复制相似问题