Skip to main content
 首页 » 编程设计

python之Pandas 的内置、无索引、漂亮的列输出

2024年10月01日14落叶

我经常发现自己在调试或研究我在 pandas 中的数据时编写这样的代码以获得格式良好的多列输出(没有索引):

   dfs = dfs[dfs['some_id'] == the_id] 
    cols = [ 
      'some_col', 
      'another_col', 
      'yet_another', 
    ] 
 
    print("\t".join(cols)) 
    for row in dfs[cols].values: 
      print("\t\t".join([str(val) for val in row])) 

这很好用,但我想知道是否有一种内置方法可以使用 pandas 函数或直接查找语法来获取此类输出。示例输出:

some_col    another_col    yet_another 
a           b              c 
x           y              z 

请您参考如下方法:

是的,您可以调用df.to_string使用参数 index=False。

dfs = dfs[dfs['some_id'] == the_id] 
    cols = [ 
      'some_col', 
      'another_col', 
      'yet_another', 
    ] 
 
print(dfs[cols].to_string(index=False)) 

MCVE:

print(df) 
 
          0         1 
0  0.335232 -1.256177 
1 -1.367855  0.746646 
2  0.027753 -1.176076 
3  0.230930 -0.679613 
4  1.261967  0.570967 
 
print(df.to_string(index=False, col_space=10)) 
 
0          1 
 0.335232  -1.256177 
-1.367855   0.746646 
 0.027753  -1.176076 
 0.230930  -0.679613 
 1.261967   0.570967