简体   繁体   English

Pandas DataFrame 到列表列表

[英]Pandas DataFrame to List of Lists

It's easy to turn a list of lists into a pandas dataframe:将列表的列表转换为 pandas dataframe 很容易:

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]]

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]]

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.一种方法是使用df.to_json()DataFrame转换为 json,然后再次解析它。 This is cumbersome but does have some advantages, because the to_json() method has some useful options.这很麻烦,但确实有一些优点,因为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]]

I wanted to preserve the index, so I adapted the original answer to this solution:我想保留索引,所以我修改了这个解决方案的原始答案:

list_df = df.reset_index().values.tolist()

Now you can paste it somewhere else (eg to paste into a Stack Overflow question) and latter recreate it:现在您可以将其粘贴到其他地方(例如粘贴到 Stack Overflow 问题中),然后重新创建它:

pd.Dataframe(list_df, columns=['name1', ...])
pd.set_index(['name1'], inplace=True)

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 数组操作。

也许有些事情发生了变化,但这返回了一个满足我需要的 ndarrays 列表。

list(df.values)

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.注意:我在 Stack Overflow 上看到过很多案例,其中将 Pandas Series 或 DataFrame 转换为 NumPy 数组或纯 Python 列表是完全没有必要的。 If you're new to the library, consider double-checking whether the functionality you need is already offered by those Pandas objects.如果您不熟悉该库,请考虑仔细检查这些 Pandas 对象是否已经提供了您需要的功能。

To quote a comment by @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_numpySeries.to_numpy方法。

"df.values" returns a numpy array. “df.values”返回一个 numpy 数组。 This does not preserve the data types.这不会保留数据类型。 An integer might be converted to a float.整数可能会转换为浮点数。

df.iterrows() returns a series which also does not guarantee to preserve the data types. df.iterrows() 返回一个也不保证保留数据类型的系列。 See: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html请参阅: https : //pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html

The code below converts to a list of list and preserves the data types:下面的代码转换为列表列表并保留数据类型:

rows = [list(row) for row in df.itertuples()]

If you wish to convert a Pandas DataFrame to a table (list of lists) and include the header column this should work:如果您希望将Pandas DataFrame转换为表格(列表列表)并包含标题列,这应该可以工作:

import pandas as pd
def dfToTable(df:pd.DataFrame) -> list:
    return [list(df.columns)] + df.values.tolist()

Usage (in REPL):用法(在 REPL 中):

>>> df = pd.DataFrame(
             [["r1c1","r1c2","r1c3"],["r2c1","r2c2","r3c3"]]
             , columns=["c1", "c2", "c3"])
>>> df
     c1    c2    c3
0  r1c1  r1c2  r1c3
1  r2c1  r2c2  r3c3
>>> dfToTable(df)
[['c1', 'c2', 'c3'], ['r1c1', 'r1c2', 'r1c3'], ['r2c1', 'r2c2', 'r3c3']]
  1. The solutions presented so far suffer from a "reinventing the wheel" approach.迄今为止提出的解决方案受到“重新发明轮子”方法的影响。 Quoting @AMC:引用@AMC:

If you're new to the library, consider double-checking whether the functionality you need is already offered by those Pandas objects.如果您不熟悉该库,请考虑仔细检查这些 Pandas 对象是否已经提供了您需要的功能。

  1. If you convert a dataframe to a list of lists you will lose information - namely the index and columns names.如果您将数据框转换为列表列表,您将丢失信息 - 即索引和列名称。

My solution: use to_dict()我的解决方案:使用to_dict()

dict_of_lists = df.to_dict(orient='split')

This will give you a dictionary with three lists: index , columns , data .这将为您提供一个包含三个列表的字典: indexcolumnsdata If you decide you really don't need the columns and index names, you get the data with如果你决定你真的不需要列和索引名称,你会得到数据

dict_of_lists['data']

I had this problem: how do I get the headers of the df to be in row 0 for writing them to row 1 in the excel (using xlsxwriter)?我遇到了这个问题:如何将 df 的标题放在第 0 行以将它们写入 Excel 中的第 1 行(使用 xlsxwriter)? None of the proposed solutions worked, but they pointed me in the right direction.提出的解决方案都没有奏效,但它们为我指明了正确的方向。 I just needed one line more of code我只需要多一行代码

# get csv data
df = pd.read_csv(filename)

# combine column headers and list of lists of values
lol = [df.columns.tolist()] + df.values.tolist()

Not quite relate to the issue but another flavor with same expectation与该问题不太相关,但具有相同期望的另一种口味

converting data frame series into list of lists to plot the chart using create_distplot in Plotly将数据框系列转换为列表列表以使用 Plotly 中的 create_distplot 绘制图表

    hist_data=[]
    hist_data.append(map_data['Population'].to_numpy().tolist())

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我们可以成功地将给定数据框的每一行提取到一个列表中

This is very simple:这很简单:

import numpy as np

list_of_lists = np.array(df)

A function I wrote that allows including the index column or the header row :我写的 function 允许包含索引列header 行

def df_to_list_of_lists(df, index=False, header=False):
    rows = []
    if header:
        rows.append(([df.index.name] if index else []) + [e for e in df.columns])
    for row in df.itertuples():
        rows.append([e for e in row] if index else [e for e in row][1:])
    return rows

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM