在Pandas DataFram的字符串中打印换行

2024-05-20 19:34:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Pandas数据框,其中一列包含string元素,而那些string元素包含我想逐字打印的新行。但它们只是作为\n出现在输出中。

也就是说,我想打印这个:

  pos     bidder
0   1
1   2
2   3  <- alice
       <- bob
3   4

但我得到的是:

  pos            bidder
0   1
1   2
2   3  <- alice\n<- bob
3   4

我怎样才能实现我想要的?我可以使用数据帧,还是必须恢复为一次手动打印一行填充列?

以下是我目前掌握的情况:

n = 4
output = pd.DataFrame({
    'pos': range(1, n+1),
    'bidder': [''] * n
})
bids = {'alice': 3, 'bob': 3}
used_pos = []
for bidder, pos in bids.items():
    if pos in used_pos:
        arrow = output.ix[pos, 'bidder']
        output.ix[pos, 'bidder'] = arrow + "\n<- %s" % bidder
    else:
        output.ix[pos, 'bidder'] = "<- %s" % bidder
print(output)

Tags: 数据inpos元素pandasoutputstring手动
1条回答
网友
1楼 · 发布于 2024-05-20 19:34:52

如果你想在ipython笔记本上这样做,你可以:

from IPython.display import display, HTML

def pretty_print(df):
    return display( HTML( df.to_html().replace("\\n","<br>") ) )
网友
2楼 · 发布于 2024-05-20 19:34:52

使用pandas.set_properties()和CSSwhite-space属性

[用于IPython笔记本电脑]

另一种方法是使用pandas的pandas.io.formats.style.Styler.set_properties()方法和CSS ^{}属性:

from IPython.display import display

# Assuming the variable df contains the relevant DataFrame
display(df.style.set_properties(**{
    'white-space': 'pre-wrap',
})

要保持文本左对齐,您可能需要添加'text-align': 'left',如下所示:

from IPython.display import display

# Assuming the variable df contains the relevant DataFrame
display(df.style.set_properties(**{
    'text-align': 'left',
    'white-space': 'pre-wrap',
})

网友
3楼 · 发布于 2024-05-20 19:34:52

来自pandas.DataFramedocumention

Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure

所以没有索引就不能有行。换行符“\n”在数据帧中不起作用。

您可以用空值覆盖'pos',并在下一行输出下一个'bidder'。但每次这样做时,索引和“pos”都会被抵消。比如:

  pos    bidder
0   1          
1   2          
2   3  <- alice
3        <- bob
4   5   

因此,如果一个名为“frank”的竞拍者的值是4,那么它将覆盖“bob”。这会导致问题,因为你添加更多。也许可以使用DataFrame和编写代码来解决这个问题,但可能值得研究其他解决方案。

下面是生成上述输出结构的代码。

import pandas as pd

n = 5
output = pd.DataFrame({'pos': range(1, n + 1),
                      'bidder': [''] * n},
                      columns=['pos', 'bidder'])
bids = {'alice': 3, 'bob': 3}
used_pos = []
for bidder, pos in bids.items():
    if pos in used_pos:
        output.ix[pos, 'bidder'] = "<- %s" % bidder
        output.ix[pos, 'pos'] = ''
    else:
        output.ix[pos - 1, 'bidder'] = "<- %s" % bidder
        used_pos.append(pos)
print(output)

编辑:

另一个选择是重组数据和输出。你可以 将pos作为列,并为每个键/人创建一个新行 在数据中。在下面的代码示例中,它用NaN打印数据帧 值替换为空字符串。

import pandas as pd

data = {'johnny\nnewline': 2, 'alice': 3, 'bob': 3,
        'frank': 4, 'lisa': 1, 'tom': 8}
n = range(1, max(data.values()) + 1)

# Create DataFrame with columns = pos
output = pd.DataFrame(columns=n, index=[])

# Populate DataFrame with rows
for index, (bidder, pos) in enumerate(data.items()):
    output.loc[index, pos] = bidder

# Print the DataFrame and remove NaN to make it easier to read.
print(output.fillna(''))

# Fetch and print every element in column 2
for index in range(1, 5):
    print(output.loc[index, 2])

但这取决于你想对数据做什么。祝你好运:)

相关问题 更多 >