在熊猫系列数据中,如何根据函数返回的数据获取密钥?



我有一个工作脚本,可以在文件中创建每行文本的数组。此数据被传递给熊猫Series()。函数 startswith("n") 用于返回每个字符串的布尔TrueFalse,以确定它是否以 n(空行(开头。 我目前正在使用计数器i和条件语句来迭代和匹配startswith()函数返回的位置。

import pandas as pd
import numpy as np
f = open('list-of-strings.txt','r')
lines = []
for line in f.xreadlines():
    lines.append(line)
s = pd.Series(lines)
i = 0
for b in s.str.startswith("n"):
    if b == 0:
        print s[i],; i += 1
    else:
        i += 1

我已经意识到我正在从两个不同的方面来看待这个问题。一种是在startswith()函数评估每个项目时直接处理每个项目。由于 startswith() 函数返回布尔值,因此可以允许根据返回的值直接处理数据。像for each item in startswith(), if value returned is True, index = current_index, print s[index].

除了能够仅打印被startswith()评估为False的字符串外,我如何从startswith()中获取当前键值?

参考资料:
https://www.tutorialspoint.com/python_pandas/python_pandas_series.htm https://www.tutorialspoint.com/python_pandas/python_pandas_working_with_text_data.htm

你的问题实际上似乎比标题中的问题简单。您尝试获取某些谓词正值的值的索引,而不是将索引传递给函数。

在熊猫中,最后一个街区

i = 0
for b in s.str.startswith("n"):
    if b == 0:
        print s[i],; i += 1
    else:
        i += 1

相当于

print(s[~s.str.startswith('n')].values)

此外,您根本不需要熊猫:

print(''.join([l for l in in open('list-of-strings.txt','r') if not l.startswith('n')]))

应该替换问题中的整个代码块。

最新更新