pandas Panda Dataframe 打印到控制台,无列名[重复]

niwlg2el  于 2023-02-11  发布在  其他
关注(0)|答案(4)|浏览(184)
    • 此问题在此处已有答案**:

Convert Pandas dataframe to csv string(2个答案)
How do you remove the column name row when exporting a pandas DataFrame?(3个答案)
3天前关闭。
我有一个 Dataframe ,如下所示:

0       1       2       3       4       5       6       7       8  class
0   0.4444  0.0000  0.0000  0.0000  0.1111  0.0000  0.2222  0.0000  0.0000      0
1   0.4444  0.3333  0.3333  0.4444  0.6667  1.0000  0.2222  0.1111  0.0000      0
2   0.2222  0.0000  0.0000  0.0000  0.1111  0.1111  0.2222  0.0000  0.0000      0

所有我想这是打印在控制台没有换行符和列名:

0.4444,0.0000,0.0000,0.0000,0.1111,0.0000,0.2222,0.0000,0.0000,0
0.4444,0.3333,0.3333,0.4444,0.6667,1.0000,0.2222,0.1111,0.0000,0
0.2222,0.0000,0.0000,0.0000,0.1111,0.1111,0.2222,0.0000,0.0000,0
..

总共有360行。
我是Pandas新手,不知道如何实现这一点。我试过将Pandas转换为numpy数组,列表,并尝试用print(data, end='')打印,但没有一个对我有效。

已解决:

如果任何人遇到类似的问题,使用df_to_csvsys.stdout解决:df.to_csv(sys.stdout, header=False, index=False, float_format='%.4f')

yruzcnhs

yruzcnhs1#

df.to_string(index=False, header=False)

这意味着,将 Dataframe 转换为字符串,但不包含索引标签和列(标题)标签。

i7uaboj4

i7uaboj42#

我尝试这样做,我可以找到这个代码:

def print_df(df):
   # This code delete index and columns names
   df_ = df.copy()
   df_.columns = ['', '', '', '']
   df_.index = ['' for _ in range(len(df))]
   print(df_)

print_df(df)

其他方式,我发现,但没有正确的空格值之间的列格式:

[print(*row, sep=', ') for row in df.values.tolist()];
fsi0uk1n

fsi0uk1n3#

问:如何打印没有列的panda Dataframe
答:
print('\n'.join(df.to_string(index = False).split('\n')[1:]))
解释:
dfstr   = df.to_string(index = False) # Make str, possibly remove index
dfrows  = dfstr.split('\n')           # split on rows
dfprint = dfrows[1:]                  # Do not print row 0 (columns)
dfp     = '\n'.join(dfprint)          # Create a single string again
hujrc8aj

hujrc8aj4#

您可以在循环中使用print值,f-string s表示小数点后3位数,join

for x in df.values:
    print (','.join(f'{y:.4f}' for y in x))

0.4444,0.0000,0.0000,0.0000,0.1111,0.0000,0.2222,0.0000,0.0000,0.0000
0.4444,0.3333,0.3333,0.4444,0.6667,1.0000,0.2222,0.1111,0.0000,0.0000
0.2222,0.0000,0.0000,0.0000,0.1111,0.1111,0.2222,0.0000,0.0000,0.0000

如果不需要换行符,则获取一行数据:

for x in df.values:
    print (','.join(f'{y:.4f}' for y in x), end='')

0.4444,0.0000,0.0000,0.0000,0.1111,0.0000,0.2222,0.0000,0.0000,0.00000.4444,0.3333,0.3333,0.4444,0.6667,1.0000,0.2222,0.1111,0.0000,0.00000.2222,0.0000,0.0000,0.0000,0.1111,0.1111,0.2222,0.0000,0.0000,0.0000

相关问题