python - 使用 Python 从一系列列表中选择项目

标签 python list pandas series

我希望能够使用 python 选择一系列列表的某些部分

我目前有一个如下所示的数据集

0    [s, d, g]
1    [f, g, d]
2       [d, s]
dtype: object

我希望能够为每一行选择其中的一个子集。在我的特定情况下,我希望能够选择前两个条目。因此,要创建一个看起来像这样的系列

0    [s, d]
1    [f, g]
2    [d, s]
dtype: object

我已经尝试过

for i in Series:
    i = Series[:1]

以及类似的事情

Series = Series[[:1]]

但显然我真的不知道我在这里做什么

最佳答案

使用indexing with str :

s = pd.Series(['s d g','f g d','d s']).str.split()
print (s)
0    [s, d, g]
1    [f, g, d]
2       [d, s]
dtype: object

s1 = s.str[:2]
print (s1)
0    [s, d]
1    [f, g]
2    [d, s]
dtype: object

关于python - 使用 Python 从一系列列表中选择项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44155384/

相关文章:

python - 为什么 dict.get(key) 而不是 dict[key]?

python - 如何为扩展模块指定不同的名称?

python - 在 Tensorflow 中重新训练模型

python - 查找重复的文件名,并且只使用 python 保留最新文件

python - 多索引数据框中列之间的数学运算

python - 操纵 Pandas 中的日期

python - 使用正则表达式删除 pandas 列中的特殊字符

java - 如何从文件中读取ArrayLists列表?

python - 使用 lambda 访问列表中字典的值

python - 为 python/pandas 中的每一行分配组平均值