Pandas groupby 以创建新数据框并将值作为列
Pandas groupby to create new dataframe with values as columns
我想按 Python 中的日期将数据重塑为数据框。
必填:
有Pandas功能吗?
一种方法是对从键列中的唯一值派生的序列使用 pandas.concat
。
这是一个最小的例子。
import pandas as pd
df = pd.DataFrame({'Col1': ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'],
'Col2': [1, 2, 3, 4, 5, 6, 7, 8]})
res = pd.concat({k: df.loc[df['Col1']==k, 'Col2'].reset_index(drop=True)
for k in df['Col1'].unique()}, axis=1)
print(res)
A B C
0 1 4.0 6
1 2 5.0 7
2 3 NaN 8
使用 cumcount
创建额外的密钥,然后我们做 pivot
,数据来自 jpp
df.assign(key=df.groupby('Col1').cumcount()).pivot('key','Col1','Col2')
Out[29]:
Col1 A B C
key
0 1.0 4.0 6.0
1 2.0 5.0 7.0
2 3.0 NaN 8.0
我想按 Python 中的日期将数据重塑为数据框。
必填:
有Pandas功能吗?
一种方法是对从键列中的唯一值派生的序列使用 pandas.concat
。
这是一个最小的例子。
import pandas as pd
df = pd.DataFrame({'Col1': ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'],
'Col2': [1, 2, 3, 4, 5, 6, 7, 8]})
res = pd.concat({k: df.loc[df['Col1']==k, 'Col2'].reset_index(drop=True)
for k in df['Col1'].unique()}, axis=1)
print(res)
A B C
0 1 4.0 6
1 2 5.0 7
2 3 NaN 8
使用 cumcount
创建额外的密钥,然后我们做 pivot
,数据来自 jpp
df.assign(key=df.groupby('Col1').cumcount()).pivot('key','Col1','Col2')
Out[29]:
Col1 A B C
key
0 1.0 4.0 6.0
1 2.0 5.0 7.0
2 3.0 NaN 8.0