【问题标题】:How to reshape dataframe if they have same index?如果它们具有相同的索引,如何重塑数据框?
【发布时间】:2017-08-14 15:18:17
【问题描述】:

如果我有像

这样的数据框
df= pd.DataFrame(['a','b','c','d'],index=[0,0,1,1])
0 0个 0 b 1摄氏度 1天

如何根据如下索引重塑数据框,即

df= pd.DataFrame([['a','b'],['c','d']],index=[0,1])
0 1 0个 1 天

【问题讨论】:

  • 你需要我做什么?
  • 如果我有多个列,这将不起作用。这与另一个问题非常相似。
  • 我会尝试提出新问题

标签: python pandas


【解决方案1】:

让我们使用set_indexgroupbycumcountunstack

df.set_index(df.groupby(level=0).cumcount(), append=True)[0].unstack()

输出:

   0  1
0  a  b
1  c  d

【讨论】:

  • 逐个字符与我相同...除了我在逗号、pep 标准和所有 (-:
  • 你不会相信 - 我有相同的解决方案,但你更快......;)
  • 谢谢先生的回答。
  • @Scott Boston 你能尝试多列的解决方案吗?我现在卡住了
  • @ScottBoston 我把它作为一个单独的问题stackoverflow.com/questions/46467416/…
【解决方案2】:

您可以将pivotcumcount 一起使用:

a = df.groupby(level=0).cumcount()
df = pd.pivot(index=df.index, columns=a, values=df[0])

【讨论】:

  • 如果我有多个列,这将不起作用。任何改进
【解决方案3】:

几种方法

1.

In [490]: df.groupby(df.index)[0].agg(lambda x: list(x)).apply(pd.Series)
Out[490]:
   0  1
0  a  b
1  c  d

2.

In [447]: df.groupby(df.index).apply(lambda x: pd.Series(x.values.tolist()).str[0])
Out[447]:
   0  1
0  a  b
1  c  d

3.

In [455]: df.assign(i=df.index, c=df.groupby(level=0).cumcount()).pivot('i', 'c', 0)
Out[455]:
c  0  1
i
0  a  b
1  c  d

删除名字

In [457]: (df.assign(i=df.index, c=df.groupby(level=0).cumcount()).pivot('i', 'c', 0)
           .rename_axis(None).rename_axis(None, 1))
Out[457]:
   0  1
0  a  b
1  c  d

【讨论】:

  • 感谢 John 让我知道这些选项。
  • 当涉及到多列时我被卡住了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-02
  • 1970-01-01
相关资源
最近更新 更多