Skip to main content
 首页 » 编程设计

python之如何从 python 中的行列表中选择特定元素

2024年09月07日7rubylouvre

我有以下系列 (df):

Index    Information 
1        [2, A, C] 
2        [3, B, C] 
3        [4, C, H] 
4        [5, D, H] 
5        [6, E, H] 
6        [7, F, H] 

我想要一个只提取和存储每个列表的第三个值的系列:

Index    Information 
1        [C] 
2        [C] 
3        [H] 
4        [H] 
5        [H] 
6        [H] 

如果我尝试 df[0][2],它正确地给出了所需的输出[C]。

但是,如果我尝试 df[:][2],而不是给出

[C] 
[C] 
[H] 
[H] 
[H] 
[H] 

输出是

3        [4, C, H] 

正确的语法应该是什么?

请您参考如下方法:

pandas.Series.str

df.Information.str[2:3] 
 
0    [C] 
1    [C] 
2    [H] 
3    [H] 
4    [H] 
5    [H] 
Name: Information, dtype: object 

使用赋值

df.assign(Information=df.Information.str[2:3]) 
 
   Index Information 
0      1         [C] 
1      2         [C] 
2      3         [H] 
3      4         [H] 
4      5         [H] 
5      6         [H] 

理解 @coldspeed

df.assign(Information=[l[2:3] for l in df.Information.tolist()]) 
 
   Index Information 
0      1         [C] 
1      2         [C] 
2      3         [H] 
3      4         [H] 
4      5         [H] 
5      6         [H]