Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python列表列表?_Python_List_Pandas_Dataframe - Fatal编程技术网

如何使用python列表列表?

如何使用python列表列表?,python,list,pandas,dataframe,Python,List,Pandas,Dataframe,我有以下列表示例: In [] : list1 Out [] : [[1.0], [2.1], [3.3, 5.5, 0.69], [0.69, 0.9]] 我只想提取元素数等于或大于2的子列表,并希望将它们存储在数据帧中 因此,我预计df如下所示: In [] : df Out [] : seq_no items 1 3.3 , 5.5, 0.69 2 0.69, 0.9 尝试

我有以下列表示例:

In [] : list1
Out [] : 
[[1.0],
 [2.1],
 [3.3, 5.5, 0.69],
 [0.69, 0.9]]
我只想提取元素数等于或大于2的子列表,并希望将它们存储在数据帧中

因此,我预计df如下所示:

In [] : df
Out [] : 
        seq_no       items
            1        3.3 , 5.5, 0.69
            2        0.69, 0.9
尝试:

item for item in list1 where(len(item) >2)
显示错误

如果有什么不清楚的地方,请告诉我。

应该这样做(有一个列表):

然后你可以加上

df.index += 1 
如果愿意,可以调整起始索引

In [755]: df = pd.DataFrame({'items': [x for x in list1 if len(x)>=2]})

In [756]: df
Out[756]:
              items
0  [3.3, 5.5, 0.69]
1       [0.69, 0.9]
添加,
序号

In [759]: df['seq_no'] = df.index + 1

In [760]: df
Out[760]:
              items  seq_no
0  [3.3, 5.5, 0.69]       1
1       [0.69, 0.9]       2
如果需要逗号分隔的字符串

In [769]: pd.DataFrame({'items': [', '.join(map(str, x)) for x in list1 if len(x)>=2]})
Out[769]:
            items
0  3.3, 5.5, 0.69
1       0.69, 0.9

使用
列表理解
序列
列范围:

a = [x for x in L if len(x) >=2]
df = pd.DataFrame({'seq':range(1, len(a)+1), 'items':a}, columns=['seq','items'])
print (df)
   seq                items
0    1     [3.3, 5.5, 0.69]
1    2     [0.69, 0.9]

您可以先将其存储在
pd.Series
中,然后进行过滤和转换

s = pd.Series(list1)
pd.DataFrame(s[s.str.len().ge(2)].tolist())

      0     1     2
0  0.00  0.50  0.69
1  0.69  0.88  1.00
2  1.00  1.10   NaN
3  1.10  2.00   NaN
4  2.00  2.50  2.90

并加入他们

s = pd.Series(list1)
s[s.str.len().ge(2)].apply(lambda x: ', '.join(map(str, x)))

2      0.0, 0.5, 0.69
3     0.69, 0.88, 1.0
4            1.0, 1.1
8            1.1, 2.0
10      2.0, 2.5, 2.9
dtype: object

您可以使用列表理解功能筛选列表。filter()或列表理解功能会有所帮助。不会,因为它会更改列的顺序。非常感谢,第一部分是我所期望的,即items列下的所有值。这符合我的建议,但更好!不过我想OP希望他们加入。非常感谢,太完美了!!
s = pd.Series(list1)
s[s.str.len().ge(2)].apply(lambda x: ', '.join(map(str, x)))

2      0.0, 0.5, 0.69
3     0.69, 0.88, 1.0
4            1.0, 1.1
8            1.1, 2.0
10      2.0, 2.5, 2.9
dtype: object