pandas 熊猫数据框和多行值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50644066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:38:01  来源:igfitidea点击:

pandas dataframe and multi line values

pythonpandasdataframe

提问by disserman

Good day,

再会,

Is it possible to get multi line cell output when using pandas DataFrame in a shell? I understand the whole row will have height more than 1 char, but that's what I actually want.

在shell中使用pandas DataFrame时是否可以获得多行单元格输出?我知道整行的高度将超过 1 个字符,但这正是我真正想要的。

Example:

例子:

data = [
       {'id': 1, 't': 'very long text\ntext line 2\ntext line 3'},
       {'id': 2, 't': 'short text'}
       ]
df = pd.DataFrame(data)
df.set_index('id', inplace=True)
print(df)

and want to get output:

并想获得输出:

id                  t
1      very long text
       text line 2
       text line 3
2      short text

instead of

代替

id                                         t
1     very long text\ntextline 2\ntext line3
2                                 short text

回答by J. Doe

You will get your expected result with

你会得到你预期的结果

df.t.str.split("\n", expand=True).stack()

回答by YOBEN_S

You can unnest your string with Seriesafter str.split

您可以使用Seriesafter取消嵌套您的字符串str.split

df.set_index('id').t.str.split(r'\n').apply(pd.Series).stack().reset_index(level=1,drop=True).to_frame('t')
Out[177]: 
                 t
id                
1   very long text
1      text line 2
1      text line 3
2       short text

回答by Yo_Chris

Look at this answer from @unsorted here Pretty printing newlines inside a string in a Pandas DataFrame

看看@unsorted 这里的答案在 Pandas DataFrame 的字符串中漂亮地打印换行符

here it is with you example:

这是你的例子:

import pandas as pd
from IPython.display import display, HTML

def pretty_print(df):
    return display(HTML(df.to_html().replace("\n","<br>")))

data = [
       {'id': 1, 't': 'very long text\ntext line 2\ntext line 3'},
       {'id': 2, 't': 'short text'}
       ]
df = pd.DataFrame(data)
df.set_index('id', inplace=True)

pretty_print(df)

         t
id  
1   very long text
    text line 2
    text line 3
2   short text