如何将数据框转换为一系列列表?

时间:2016-08-02 06:29:48

标签: python list pandas dataframe series

我不得不多次这样做,我总是感到沮丧。我有一个数据框:

df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], ['a', 'b'], ['A', 'B', 'C', 'D'])

print df

   A  B  C  D
a  1  2  3  4
b  5  6  7  8

我想将df变为:

pd.Series([[1, 2, 3, 4], [5, 6, 7, 8]], ['a', 'b'])

a    [1, 2, 3, 4]
b    [5, 6, 7, 8]
dtype: object

我试过

df.apply(list, axis=1)

这让我回到同一个df

这样做的方便/有效方法是什么?

3 个答案:

答案 0 :(得分:20)

您可以先DataFramenumpy array转换为Series,然后转换为列表,如果需要更快的解决方案,最后创建一个索引来自df的新print (pd.Series(df.values.tolist(), index=df.index)) a [1, 2, 3, 4] b [5, 6, 7, 8] dtype: object

In [76]: %timeit (pd.Series(df.values.tolist(), index=df.index))
1000 loops, best of 3: 295 µs per loop

In [77]: %timeit pd.Series(df.T.to_dict('list'))
1000 loops, best of 3: 685 µs per loop

In [78]: %timeit df.T.apply(tuple).apply(list)
1000 loops, best of 3: 958 µs per loop

使用小型DataFrame进行计时:

from string import ascii_letters
letters = list(ascii_letters)
df = pd.DataFrame(np.random.choice(range(10), (52 ** 2, 52)),
                  pd.MultiIndex.from_product([letters, letters]),
                  letters)

In [71]: %timeit (pd.Series(df.values.tolist(), index=df.index))
100 loops, best of 3: 2.06 ms per loop

In [72]: %timeit pd.Series(df.T.to_dict('list'))
1 loop, best of 3: 203 ms per loop

In [73]: %timeit df.T.apply(tuple).apply(list)
1 loop, best of 3: 506 ms per loop

和大:

public static bool XMLToPDF(string pXmlFile, string pXslFile, string pFoFile, string pPdfFile)
{
    string lBaseDir = System.IO.Path.GetDirectoryName(pXslFile);
    XslCompiledTransform lXslt = new XslCompiledTransform();
    lXslt.Load(pXslFile);
    lXslt.Transform(pXmlFile, pFoFile);
    FileStream lFileInputStreamFo = new FileStream(pFoFile, FileMode.Open);
    FileStream lFileOutputStreamPDF = new FileStream(pPdfFile, FileMode.Create);
    FonetDriver lDriver = FonetDriver.Make();
    lDriver.BaseDirectory = new DirectoryInfo(lBaseDir);
    lDriver.CloseOnExit = true;
    lDriver.Render(lFileInputStreamFo, lFileOutputStreamPDF);
    lFileInputStreamFo.Close();
    lFileOutputStreamPDF.Close();
    return System.IO.File.Exists(pPdfFile);
}

答案 1 :(得分:8)

pandas尝试使数据帧很方便。因此,它将列表和数组解释为您希望拆分为列的内容。我不会抱怨,这几乎总是有帮助的。

我已经完成了以下两种方式之一。

选项1

# Only works with a non MultiIndex
# and its slow, so don't use it
df.T.apply(tuple).apply(list)

选项2

pd.Series(df.T.to_dict('list'))

两者都给你:

a    [1, 2, 3, 4]
b    [5, 6, 7, 8]
dtype: object

然而 选项2 可以更好地扩展。

时序

给定df

enter image description here

大得多df

from string import ascii_letters
letters = list(ascii_letters)
df = pd.DataFrame(np.random.choice(range(10), (52 ** 2, 52)),
                  pd.MultiIndex.from_product([letters, letters]),
                  letters)

df.T.apply(tuple).apply(list)的结果是错误的,因为该解决方案不适用于MultiIndex。

enter image description here

答案 2 :(得分:0)

列出转化的数据框

List_name =df_name.values.tolist()
相关问题