Python 将数据帧值转换为1D列表

Python 将数据帧值转换为1D列表,python,list,pandas,dataframe,Python,List,Pandas,Dataframe,我有一个数据框,如下所示: V Out[58]: P1 P2 P3 V1 a b c V2 f g h V3 k l m 我想将它们全部存储在列表L中,以便: L=[a,b,c,f,g,h,k,l,m] 从一行迭代到另一行。你知道怎么做吗?谢谢使用ndarray访问.values属性、重塑形状并转换为列表。tolist: df.values.reshape(-1,).tolist() ['a', 'b', 'c', 'f', 'g', 'h'

我有一个数据框,如下所示:

V
Out[58]: 

     P1 P2 P3 

V1   a  b  c  
V2   f  g  h  
V3   k  l  m
我想将它们全部存储在列表L中,以便:

L=[a,b,c,f,g,h,k,l,m]

从一行迭代到另一行。你知道怎么做吗?谢谢

使用
ndarray访问
.values
属性、重塑形状并转换为列表。tolist

df.values.reshape(-1,).tolist()
['a', 'b', 'c', 'f', 'g', 'h', 'k', 'l', 'm']
另一个是
stack
ing,然后是直接
tolist
调用:

df.stack().tolist()
['a', 'b', 'c', 'f', 'g', 'h', 'k', 'l', 'm']

使用
ndarray访问
.values
属性,重塑形状并转换为列表。tolist

df.values.reshape(-1,).tolist()
['a', 'b', 'c', 'f', 'g', 'h', 'k', 'l', 'm']
另一个是
stack
ing,然后是直接
tolist
调用:

df.stack().tolist()
['a', 'b', 'c', 'f', 'g', 'h', 'k', 'l', 'm']

这样做很方便:

from itertools import chain
import pandas as pd

df = pd.DataFrame([['a', 'b', 'c'],
                   ['f', 'g', 'h'],
                   ['k', 'l', 'm']],
                  columns=['P1', 'P2', 'P3'],
                  index=['V1', 'V2', 'V3'])

res = list(chain.from_iterable(df.values))

# ['a', 'b', 'c', 'f', 'g', 'h', 'k', 'l', 'm']
这样做很方便:

from itertools import chain
import pandas as pd

df = pd.DataFrame([['a', 'b', 'c'],
                   ['f', 'g', 'h'],
                   ['k', 'l', 'm']],
                  columns=['P1', 'P2', 'P3'],
                  index=['V1', 'V2', 'V3'])

res = list(chain.from_iterable(df.values))

# ['a', 'b', 'c', 'f', 'g', 'h', 'k', 'l', 'm']

使用
tolist
sum

sum(df.values.tolist(),[])
Out[65]: ['a', 'b', 'c', 'f', 'g', 'h', 'k', 'l', 'm']

使用
tolist
sum

sum(df.values.tolist(),[])
Out[65]: ['a', 'b', 'c', 'f', 'g', 'h', 'k', 'l', 'm']

@DChy无需担心。@DChy无需担心。最好使用
chain.from iterable(df.values)
,这样您就不必解压列表。无需使用
dis
,只需
df=pd.concat([df]*100000)
并进行几次测试,您就会明白。最好使用
chain.from iterable(df.values)
,因此,您不必解包列表。无需
dis
,只需
df=pd.concat([df]*100000)
并进行几次timeit测试,您就会明白。