我正在尝试调整当前的两列数据框,目前看起来像这样:
one two
a 12
b 32
c 12
我想透视它,导致两列都不成为索引。我的预期结果是:
a b c
12 32 12
a,b和c是新列。 12,32,12是行中的值。
谢谢
使用set_index
将列'one'移动到索引中,然后使用T
进行转置。
a.set_index('one').T
输出:
one a b c
two 12 32 12
信息:
<class 'pandas.core.frame.DataFrame'>
Index: 1 entries, two to two
Data columns (total 3 columns):
a 1 non-null int64
b 1 non-null int64
c 1 non-null int64
dtypes: int64(3)
memory usage: 28.0+ bytes
None
如果这是您的输入:
a = pd.DataFrame([("a", 12), ("b", 32), ("c", 12)], columns=["one", "two"])
one two
0 a 12
1 b 32
2 c 12
然后a.transpose()
导致这个:
0 1 2
one a b c
two 12 32 12
这是你在找什么?
使用.pivot_table
为所有内容提供相同的索引
df.pivot_table(columns='one', index=df.index//len(df), values='two').rename_axis(None, axis=1)
#or with pivot
df = df.pivot(columns='one', index=df.index//len(df)).rename_axis([None, None], axis=1)
df.columns = [y for _,y in df.columns]
a b c
0 12 32 12