【问题标题】:Badly aligned output when printing an rpy2 stem and leaf plot打印 rpy2 茎叶图时输出对齐错误
【发布时间】:2018-02-03 10:39:58
【问题描述】:

我正在尝试使用 rpy2 在 python 中绘制茎叶图,该图显示在我的输出中,但排列不正确,因为您可以看到输出中有一些不必要的中断,而某些输出应该全部是在同一行(见下文)。怎么能补救呢?

import pandas as pd
import numpy as np
from rpy2.robjects import r, pandas2ri, numpy2ri

pandas2ri.activate()  # Lets me convert pandas data frame to r
numpy2ri.activate()  # Lets me use numpy arrays in r functions s

df = pd.DataFrame(r['iris'])  # Convert r's iris data set to a pandas 

#  Set column names
attributes = ["sepal_length", "sepal_width", "petal_length", 
"petal_width", "class"]
df.columns = attributes

# Get list of sepal widths of versicolor
df_versicolor = df.loc[df['class'] == "versicolor"]
versicolor_sepal_width = df_versicolor["sepal_width"].tolist()
versicolor_sepal_width = np.array(versicolor_sepal_width) 


# Stem and leaf plot
r_stem_and_leaf = r['stem']
stem = r_stem_and_leaf(example)

还有输出,对齐不好

       The decimal point is 
1 digit(s) to the left of the |


  20 | 
0


  22 | 
0
0
0
0
0


  24 | 
0
0
0
0
0
0
0


  26 | 
0
0
0
0
0
0
0
0


  28 | 
0
0
0
0
0
0
0
0
0
0
0
0
0


  30 | 
0
0
0
0
0
0
0
0
0
0
0


  32 | 
0
0
0
0


  34 | 
0

【问题讨论】:

  • stem 函数会隐式打印它,但使用 print 会得到相同的结果。
  • 并且新行中的所有尾随 0 都应该是内联的,在 | 的右侧

标签: python r rpy2


【解决方案1】:

显然,这是一个 Python 控制台输出渲染。考虑将输出(借用 @Jfs's answer)重定向到字符串值,然后像 R 那样替换漂亮打印的换行符:

...
# Stem and leaf plot    
from io import StringIO
from contextlib import redirect_stdout

with StringIO() as buf, redirect_stdout(buf):
    stem = r['stem'](df_versicolor['sepal_width'])  # DF COLUMN CAN BE USED
    output = buf.getvalue()

print(output.replace('\n','').replace('  ', '\n'))

# The decimal point is 1 digit(s) to the left of the |
# 20 | 0
# 22 | 00000
# 24 | 0000000
# 26 | 00000000
# 28 | 0000000000000
# 30 | 00000000000
# 32 | 0000
# 34 | 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多