簡體   English   中英

將pandas數據框索引重塑為列

[英]reshape a pandas dataframe index to columns

考慮下面的pandas Series對象,

index = list('abcdabcdabcd')
df = pd.Series(np.arange(len(index)), index = index)

我想要的輸出是

   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11

我對pd.pivot_table和pd.unstack付出了一些努力,而解決方案可能在於正確使用其中之一。 我最接近的是

df.reset_index(level = 1).unstack(level = 1)

但這沒有給我我想要的輸出

//這甚至更接近所需的輸出,但是我無法處理索引分組。

df.to_frame().set_index(df1.values, append = True, drop  = False).unstack(level = 0)

     a    b     c     d
0   0.0  NaN   NaN   NaN
1   NaN  1.0   NaN   NaN
2   NaN  NaN   2.0   NaN
3   NaN  NaN   NaN   3.0
4   4.0  NaN   NaN   NaN
5   NaN  5.0   NaN   NaN
6   NaN  NaN   6.0   NaN
7   NaN  NaN   NaN   7.0
8   8.0  NaN   NaN   NaN
9   NaN  9.0   NaN   NaN
10  NaN  NaN  10.0   NaN
11  NaN  NaN   NaN  11.0

有點使用更多通用的解決方案cumcount得到新的索引值,並pivot做整形:

# Reset the existing index, and construct the new index values.
df = df.reset_index()
df.index = df.groupby('index').cumcount()

# Pivot and remove the column axis name.
df = df.pivot(columns='index', values=0).rename_axis(None, axis=1)

結果輸出:

   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11

如果索引始終以相同的順序循環,並且您知道“期間”(在本例中為4),則這是一種可行的方法:

>>> pd.DataFrame(df.values.reshape(-1,4), columns=list('abcd'))
   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
>>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM