[英]Python : Inserting hyphens after column header in Pandas
I have created a dataframe in Python Pandas as below: 我已经在Python Pandas中创建了一个数据框,如下所示:
import pandas as pd
import os
cols = ('Name','AGE','SAL')
df = pd.read_csv("C:\\Users\\agupt80\\Desktop\\POC\\Python\\test.csv",names = cols)
print(df)
When I am printing dataframe I am getting below output: 当我打印数据框时,我得到以下输出:
Name AGE SAL
0 Amit 32 100
1 gupta 33 200
2 hello 34 300
3 Amit 33 100
Please help is letting me know, how can I insert a Hyphen "-" line after column header like below: 请帮助让我知道,如何在列标题后插入连字符“-”,如下所示:
Name AGE SAL
------------------------
0 Amit 32 100
1 gupta 33 200
2 hello 34 300
3 Amit 33 100
I don't know of any pandas customization option for printing separators, but you can just print the df to a string, and then insert the line yourself. 我不知道用于打印分隔符的任何熊猫自定义选项,但是您可以仅将df打印为字符串,然后自己插入行。 Something like this:
像这样:
string_repr = df.to_string().splitlines()
string_repr.insert(1, "-" * len(string_repr[0]))
out = '\n'.join(string_repr)
>>> print(out)
Name AGE SAL
------------------
0 Amit 32 100
1 gupta 33 200
2 hello 34 300
3 Amit 33 100
You could do something like this: 您可以执行以下操作:
import pandas as pd
df = pd.DataFrame([
['Amit', 32, 100],
['gupta', 33, 200],
['hello', 34, 100],
['Amit', 33, 100]],
columns=['Name', 'AGE', 'SAL'])
lines = df.to_string().splitlines()
num_hyphens = max(len(line) for line in lines)
lines.insert(1, '-' * num_hyphens)
result = '\n'.join(lines)
print(result)
Output: 输出:
Name AGE SAL
------------------
0 Amit 32 100
1 gupta 33 200
2 hello 34 100
3 Amit 33 100
You can change the calculation of num_hyphens
depending on how exactly you want your output to look like. 您可以更改
num_hyphens
的计算,具体取决于您希望输出看起来如何。 For example you could do: 例如,您可以这样做:
num_hyphens = 2 * len(lines[0]) - len(lines[0].strip())
To get: 要得到:
Name AGE SAL
----------------------
0 Amit 32 100
1 gupta 33 200
2 hello 34 100
3 Amit 33 100
Note: If the DataFrame has a named index, to_string
will output an additional header line with the name of the index. 注意:如果DataFrame具有命名索引,则
to_string
将输出带有索引名称的附加标题行。 In that case you could choose to remove that line (replace it with the hyphens) add the hyphens after it (at position 2 instead of 1). 在这种情况下,您可以选择删除该行(用连字符替换),在其后添加连字符(在位置2而不是1)。
you need, 你需要,
#shift the values one level
df=df.shift(1)
#fill the first row with hyphen
df.iloc[0]='----'
output
Name AGE SAL
---- ---- ----
Amit3 2 100
gupta 33 200
hello 34 300
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.