![](/img/trans.png)
[英]convert python pandas dataframe with column names and index names to list of lists
[英]Create list of lists from pandas cells without index and column names
我试图从Pandas Dataframe创建一个行方式嵌套列表。 重要的方面是摆脱索引和列名称。
假设以下df:
test = pd.DataFrame({'0' : ['1','4','5','5'],
'1' : ['4','1','12','10'],
'2' : ['10','12','4','2'],
'3' : ['2','10','10','4']})
0 1 2 3
0 1 4 10 2
1 4 1 12 10
2 5 12 4 10
3 5 10 2 4
我想得到这个:
alist = [[1,4,10,2], [4,1,12,10],[5,12,4,10],[5,10,2,4]]
有任何想法吗?
提前致谢!
编辑:
这没有用,因为索引和列名也是从Dataframe派生的:
# Create an empty list
Row_list =[]
# Iterate over each row
for index, rows in df.iterrows():
# Create list for the current row
my_list =[rows.Date, rows.Event, rows.Cost]
# append the list to the final list
Row_list.append(my_list)
# Print the list
print(Row_list)
pandas.DataFrame.values会有所帮助。
在你的情况下,
test.astype('int').values
给出结果:
array([[ 1, 4, 10, 2],
[ 4, 1, 12, 10],
[ 5, 12, 4, 10],
[ 5, 10, 2, 4]])
或者如果你想转置数据帧, pandas.DataFrame.T会有所帮助:
test.astype('int').T.values
结果如下:
array([[ 1, 4, 5, 5],
[ 4, 1, 12, 10],
[10, 12, 4, 2],
[ 2, 10, 10, 4]])
好吧,你可能不需要T.
test.to_numpy('int').tolist()
输出:
[[1, 4, 10, 2], [4, 1, 12, 10], [5, 12, 4, 10], [5, 10, 2, 4]]
使用T
进行转置,转换为numpy数组和tolist
:
test.T.values.tolist()
输出:
[['1', '4', '5', '5'],
['4', '1', '12', '10'],
['10', '12', '4', '2'],
['2', '10', '10', '4']]
如果你需要整数使用to_numpy
和to_numpy
:
test.T.to_numpy('int').tolist()
输出:
[[1, 4, 5, 5], [4, 1, 12, 10], [10, 12, 4, 2], [2, 10, 10, 4]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.