如何将键与列对齐?

2024-09-25 10:28:54 发布

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

我想将pandas中的键与它们所属的列对齐。我有下面的代码和输出,以及我正在尝试做的一个示例

代码:

df = pd.read_csv('Filename.txt')
df.columns = ['Date','b1','b2','b3']
df = df.set_index('Date')

reversed_df = df.iloc[::-1]

n=5
print('Game')
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
print(reversed_df.drop(df.index[n:-n]),("\n"))

BallOne = pd.get_dummies(reversed_df.b1)
BallTwo = pd.get_dummies(reversed_df.b2)
BallThree = pd.get_dummies(reversed_df.b3)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.width', None)
print(pd.concat([BallOne, BallTwo, BallThree], keys = ['D3E-B1', 'D3E-B2', 'D3E-B3'], axis=1),("\n"))

输出:

           D3E-B1                            D3E-B2                            D3E-B3                           
                0  1  2  3  4  5  6  7  8  9      0  1  2  3  4  5  6  7  8  9      0  1  2  3  4  5  6  7  8  9
Date                                                                                                            
1984-09-01      0  0  0  0  0  0  0  0  0  1      0  0  0  0  1  0  0  0  0  0      0  0  0  0  0  0  0  0  1  0
1984-09-03      0  1  0  0  0  0  0  0  0  0      0  0  0  0  0  1  0  0  0  0      0  0  0  1  0  0  0  0  0  0

我希望这些键在它们的列上居中,如下所示:

                D3E-B1                            D3E-B2                            D3E-B3                           
                0  1  2  3  4  5  6  7  8  9      0  1  2  3  4  5  6  7  8  9      0  1  2  3  4  5  6  7  8  9
Date                                                                                                            
1984-09-01      0  0  0  0  0  0  0  0  0  1      0  0  0  0  1  0  0  0  0  0      0  0  0  0  0  0  0  0  1  0
1984-09-03      0  1  0  0  0  0  0  0  0  0      0  0  0  0  0  1  0  0  0  0      0  0  0  1  0  0  0  0  0  0

Tags: columnsnonedfgetdatedisplaymaxb1
1条回答
网友
1楼 · 发布于 2024-09-25 10:28:54
from tabulate import tabulate
import pandas as pd

df = pd.DataFrame({'col_two' : [0.0001, 1e-005 , 1e-006, 1e-007],
                   'column_3' : ['ABCD', 'ABCD', 'long string', 'ABCD']})
print(tabulate(df, headers='keys', tablefmt='psql'))

+  +     -+      -+
|    |   col_two | column_3    |
|  +     -+      -|
|  0 |    0.0001 | ABCD        |
|  1 |    1e-05  | ABCD        |
|  2 |    1e-06  | long string |
|  3 |    1e-07  | ABCD        |
+  +     -+      -+

发件人:Pretty Printing a pandas dataframe

相关问题 更多 >