格式化熊猫数据框

时间:2020-02-06 00:47:20

标签: python pandas

所以我在熊猫格式设置时遇到问题。 有任何想法吗?如果之前已经问过这个问题,请告诉我,并指出我的位置! 返回类型对我来说并不重要,只要它按照我那里的格式格式化即可。 我有以下内容,其中数字是这种情况下的索引,New是我的专栏。

   New
3  A
2  A
4  B
5  C
8  C

我想要

A
3 2 
B
4 
C
5 8

2 个答案:

答案 0 :(得分:1)

有点不同,但是您可以将列表作为值嵌套在Python DataFrame内的列中。

df = pd.DataFrame( {'new':['A','A','B','C','C'], 'val':[3,2,4,5,8]})
print(df)
     // apply a function 'list' on values and after
     // recreate a valid DataFrame where the field with lists
     // will be called 'up'

dfup = df.groupby('new')['val'].apply(list).reset_index(name='up')  
print("==============")
print(dfup)

输出为

  new  val
0   A    3
1   A    2
2   B    4
3   C    5
4   C    8
=============
  new      up
0   A  [3, 2]
1   B     [4]
2   C  [5, 8]

通常,groupby用于求和或某些其他聚合函数。

dfup = df.groupby('new').sum()

输出为:

new
A      5
B      4
C     13

答案 1 :(得分:1)

这是pivot_table()的单线。您可以将list用作aggfunc

> import pandas as pd
> df = pd.DataFrame({'New': ['A','A','B','C','C']}, index=[3,2,4,5,8])

> df.reset_index().pivot_table('index', aggfunc=list, columns='New')

New         A    B       C
index  [3, 2]  [4]  [5, 8]

# You probably want the transpose...

> df.reset_index().pivot_table('index', aggfunc=list, columns='New').T

      index
New        
A    [3, 2]
B       [4]
C    [5, 8]

这似乎已经足够接近您想要的了,但是在格式化打印时,您可以添加代码以删除列表中的括号。 (例如,将索引转换为字符串,并在其上使用字符串连接或' '.join()