一种Pythonic方式重塑Pandas.DataFrame' s

时间:2017-10-25 01:48:46

标签: python python-3.x pandas

enter image description here 我左边有一个Pandas.DataFrame。 我想将其重塑为右侧的形式。 每个标签(a,b和c)的值的数量是相同的。

我现在正在做的是创建一个新的DataFrame,然后通过添加每个列将每个标签的值附加到其上。 它肯定有用,但据我所知,Pandas.DataFrame非常强大,我相信必须有更多的Pythonic方法来完成任务。

任何帮助将不胜感激!

4 个答案:

答案 0 :(得分:5)

一种方法是使用cumcount,然后使用pivot_table

In [11]: df["count"] = df.groupby("label").cumcount()

In [12]: df
Out[12]:
  label  value  count
0     a    0.2      0
1     a    0.1      1
2     a    0.4      2
3     b    0.5      0
4     b    0.2      1
5     b    0.6      2
6     c    0.7      0
7     c    0.9      1
8     c    0.3      2

In [13]: df.pivot_table("value", "count", "label")
Out[13]:
label    a    b    c
count
0      0.2  0.5  0.7
1      0.1  0.2  0.9
2      0.4  0.6  0.3

如果您可以获得每组中的订单和编号,您可以重新塑造:

In [21]: df["value"].values.reshape((-1, 3)).T
Out[21]:
array([[ 0.2,  0.5,  0.7],
       [ 0.1,  0.2,  0.9],
       [ 0.4,  0.6,  0.3]])

您可以使用以下内容将其设为DataFrame:

In [22]: pd.DataFrame(df["value"].values.reshape((-1, 3)).T, 
                      columns=df.loc[::3, "label"])
Out[22]:
label    a    b    c
0      0.2  0.5  0.7
1      0.1  0.2  0.9
2      0.4  0.6  0.3

答案 1 :(得分:3)

做到这一点〜:-)无需创建其他专栏

    df=df.sort_values('label')# in case you do have disordered df
    pd.crosstab(df.index%3,df.label,df.value,aggfunc='sum')
    Out[600]: 
    label    a    b    c
    row_0               
    0      0.2  0.5  0.7
    1      0.1  0.2  0.9
    2      0.4  0.6  0.3

答案 2 :(得分:2)

这是我的娱乐。如果你喜欢这些答案......很好!

选项1

from collections import defaultdict
import pandas as pd

d = defaultdict(list)

for k, v in df.values.tolist():
    d[k].append(v)

pd.DataFrame(d)

     a    b    c
0  0.2  0.5  0.7
1  0.1  0.2  0.9
2  0.4  0.6  0.3

选项2

pd.concat({
    n: g.reset_index(drop=True)
    for n, g in df.groupby('label').value
}, axis=1)

     a    b    c
0  0.2  0.5  0.7
1  0.1  0.2  0.9
2  0.4  0.6  0.3

选项3

f, u = pd.factorize(df.label.values)
c = np.eye(u.size, dtype=int)[f].cumsum(0)[np.arange(f.size), f] - 1
a = np.empty((c.max() + 1, u.size))
a[c, f] = df.value.values
pd.DataFrame(a, columns=u)

     a    b    c
0  0.2  0.5  0.7
1  0.1  0.2  0.9
2  0.4  0.6  0.3

答案 3 :(得分:1)

.pivot的另一种解决方案:

res = (df.pivot(columns='label', values='value')
          .apply(lambda x: pd.Series(x.dropna().values)))
print(res)
# label    a    b    c
# 0      0.2  0.5  0.7
# 1      0.1  0.2  0.9
# 2      0.4  0.6  0.3