Pandas df.values 不返回索引值



我有一个多索引表,我想将其转换为列表。

表:(索引列 - "adsh"、"报告"、"行"(

stmt  inpth rfile                     tag  
adsh                 report line                                             
0000804753-17-000004 2      20     BS      0     H  AccountsPayableCurrent   
0000215466-17-000058 5      19     BS      0     H  AccountsPayableCurrent   
0001477932-17-000685 2      10     BS      0     H  AccountsPayableCurrent   
0001554795-17-000056 2      11     BS      0     H  AccountsPayableCurrent   
0001558370-17-000547 3      19     BS      0     H  AccountsPayableCurrent   

输入:

df.values

输出:

array([['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
'Accounts payable'],
['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
'Accounts payable'],
['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
'Accounts payable'],
['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
'Accounts payable'],
['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
'Accounts payable']], dtype=object)

我知道我也可以运行df.index.values来获取索引值的列表,但我想要的是单个列表中的索引值和列值。实现这一目标的最佳方法是什么?

to_records是你想要使用的。

df.to_records()

这将返回一个包含数据帧索引的记录数组。

各种方法可以做到这一点。一个明显的是,您创建一个复制索引数据的列,然后调用df.values

这是另一种方式(不知道这有多有效(:

df
a
0   1
1   3
2   5
3   7
4   7
5  34
6   3
7  24
np.append(np.expand_dims(df.index.values, axis=0), np.expand_dims(df.a.values, axis=0), axis=0).T
array([[ 0,  1],
[ 1,  3],
[ 2,  5],
[ 3,  7],
[ 4,  7],
[ 5, 34],
[ 6,  3],
[ 7, 24]], dtype=int64)

最新更新