Python Pandas DataFrame 到列表列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28006793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas DataFrame to List of Lists
提问by bumpkin
It's easy to turn a list of lists into a pandas dataframe:
将列表列表转换为 Pandas 数据框很容易:
import pandas as pd
df = pd.DataFrame([[1,2,3],[3,4,5]])
But how do I turn df back into a list of lists?
但是如何将 df 转回列表列表?
lol = df.what_to_do_now?
print lol
# [[1,2,3],[3,4,5]]
采纳答案by DSM
You could access the underlying array and call its tolist
method:
您可以访问底层数组并调用其tolist
方法:
>>> df = pd.DataFrame([[1,2,3],[3,4,5]])
>>> lol = df.values.tolist()
>>> lol
[[1L, 2L, 3L], [3L, 4L, 5L]]
回答by aps
I don't know if it will fit your needs, but you can also do:
我不知道它是否适合您的需求,但您也可以这样做:
>>> lol = df.values
>>> lol
array([[1, 2, 3],
[3, 4, 5]])
This is just a numpy array from the ndarray module, which lets you do all the usual numpy array things.
这只是来自 ndarray 模块的一个 numpy 数组,它可以让您执行所有常见的 numpy 数组操作。
回答by Andrew E
If the data has column and index labels that you want to preserve, there are a few options.
如果数据具有要保留的列和索引标签,则有几个选项。
Example data:
示例数据:
>>> df = pd.DataFrame([[1,2,3],[3,4,5]], \
columns=('first', 'second', 'third'), \
index=('alpha', 'beta'))
>>> df
first second third
alpha 1 2 3
beta 3 4 5
The tolist()
method described in other answers is useful but yields only the core data - which may not be enough, depending on your needs.
tolist()
其他答案中描述的方法很有用,但仅产生核心数据 - 根据您的需要,这可能还不够。
>>> df.values.tolist()
[[1, 2, 3], [3, 4, 5]]
One approach is to convert the DataFrame
to json using df.to_json()
and then parse it again. This is cumbersome but does have some advantages, because the to_json()
method has some useful options.
一种方法是使用 将 转换DataFrame
为 json df.to_json()
,然后再次解析它。这很麻烦,但确实有一些优点,因为该to_json()
方法有一些有用的选项。
>>> df.to_json()
{
"first":{"alpha":1,"beta":3},
"second":{"alpha":2,"beta":4},"third":{"alpha":3,"beta":5}
}
>>> df.to_json(orient='split')
{
"columns":["first","second","third"],
"index":["alpha","beta"],
"data":[[1,2,3],[3,4,5]]
}
Cumbersome but may be useful.
麻烦,但可能有用。
The good news is that it's pretty straightforward to build lists for the columns and rows:
好消息是,为列和行构建列表非常简单:
>>> columns = [df.index.name] + [i for i in df.columns]
>>> rows = [[i for i in row] for row in df.itertuples()]
This yields:
这产生:
>>> print(f"columns: {columns}\nrows: {rows}")
columns: [None, 'first', 'second', 'third']
rows: [['alpha', 1, 2, 3], ['beta', 3, 4, 5]]
If the None
as the name of the index is bothersome, rename it:
如果None
作为索引的名称很麻烦,请将其重命名:
df = df.rename_axis('stage')
Then:
然后:
>>> columns = [df.index.name] + [i for i in df.columns]
>>> print(f"columns: {columns}\nrows: {rows}")
columns: ['stage', 'first', 'second', 'third']
rows: [['alpha', 1, 2, 3], ['beta', 3, 4, 5]]
回答by neves
I wanted to preserve the index, so I adapted the original answer to this solution:
我想保留索引,所以我修改了这个解决方案的原始答案:
df.reset_index().values.tolist()
Now to recreate it somewhere else (e.g. to paste into a Stack Overflow question):
现在在其他地方重新创建它(例如粘贴到堆栈溢出问题中):
pd.Dataframe(<data-printed-above>, columns=['name1', ...])
pd.set_index(['name1'], inplace=True)
回答by Ian Rubenstein
Maybe something changed but this gave back a list of ndarrays which did what I needed.
也许有些事情发生了变化,但这返回了一个满足我需要的 ndarrays 列表。
list(df.values)
回答by AMC
Note:I have seen many cases on Stack Overflow where converting a Pandas Series or DataFrame to a NumPy array or plain Python lists is entirely unecessary. If you're new to the library, consider double-checking whether the functionality you need is already offered by those Pandas objects.
注意:我在 Stack Overflow 上看到过很多案例,其中将 Pandas Series 或 DataFrame 转换为 NumPy 数组或纯 Python 列表是完全没有必要的。如果您不熟悉该库,请考虑仔细检查这些 Pandas 对象是否已经提供了您需要的功能。
To quote a commentby @jpp:
引用@jpp的评论:
In practice, there's often no need to convert the NumPy array into a list of lists.
在实践中,通常不需要将 NumPy 数组转换为列表列表。
If a Pandas DataFrame/Series won't work, you can use the built-in DataFrame.to_numpy
and Series.to_numpy
methods.
如果 Pandas DataFrame/Series 不起作用,您可以使用内置DataFrame.to_numpy
和Series.to_numpy
方法。
回答by Ram Prajapati
We can use the DataFrame.iterrows() function to iterate over each of the rows of the given Dataframe and construct a list out of the data of each row:
我们可以使用 DataFrame.iterrows() 函数迭代给定 Dataframe 的每一行,并从每一行的数据中构造一个列表:
# 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
print(row_list)
We can successfully extract each row of the given data frame into a list
我们可以成功地将给定数据框的每一行提取到一个列表中
回答by Tms91
This is very simple:
这很简单:
import numpy as np
list_of_lists = np.array(df)