简体   繁体   English

格式化熊猫数据框

[英]Formatting pandas dataframe

So I'm having an issue formatting in pandas.所以我在 Pandas 中遇到了格式化问题。 Any ideas?有任何想法吗? If this has been asked before please let me know and please point me to where!如果之前有人问过这个问题,请告诉我,并请指出我在哪里! The return type doesn't matter to me as long as its formatted along the lines of what I have down there.返回类型对我来说并不重要,只要它的格式与我在那里的内容一致即可。 I have the following where the numbers are the index in this case, New is my column.在这种情况下,我有以下数字是索引,New 是我的专栏。

   New
3  A
2  A
4  B
5  C
8  C

I want我想要

A
3 2 
B
4 
C
5 8

It's a little bit different but you can nest a list as a value in a column inside a DataFrame in Python.它有点不同,但您可以将列表作为值DataFrame在 Python 的DataFrame内的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)

The output is输出是

  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]

Normally, groupby is used to sum or some other aggregate function.通常, groupby用于求和或其他一些聚合函数。

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

And the output is:输出是:

new
A      5
B      4
C     13

This is a one-liner with pivot_table() .这是一个带有pivot_table() You can use list as aggfunc :您可以使用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]

This seems close enough to what you want, but you can add code to remove the brackets around the list, when formatted for print.这似乎与您想要的非常接近,但是您可以添加代码以在格式化打印时删除列表周围的括号。 (eg convert index to string, and use string concatenate or ' '.join() on it) (例如将索引转换为字符串,并在其上使用字符串连接或' '.join()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM