小编wol*_*pha的帖子

根据对象的类型(即str)从DataFrame中选择行

所以有一个DataFrame说:

>>> df = pd.DataFrame({
...                 'A':[1,2,'Three',4],
...                 'B':[1,'Two',3,4]})
>>> df
       A    B
0      1    1
1      2  Two
2  Three    3
3      4    4
Run Code Online (Sandbox Code Playgroud)

我想选择特定列的特定行的数据类型是类型的行str.

比如我要选择的行,其中type在列中的数据Astr.所以它应该打印如下:

   A      B
2  Three  3
Run Code Online (Sandbox Code Playgroud)

谁的直观代码是这样的:

df[type(df.A) == str]
Run Code Online (Sandbox Code Playgroud)

这显然不起作用!

谢谢请帮忙!

python pandas

15
推荐指数
3
解决办法
1万
查看次数

Python `bs4.BeautifulSoup.get_text()` - 仅从直接级别获取文本

假设我有一个 HTML 片段,并且我只想get_text从直接级别开始:

from bs4 import BeautifulSoup
s = "<div><p><strong>College Type:</strong> \r\nPrivate Un-aided\r\n</p></div>"
soup = BeautifulSoup(s, 'lxml')
print soup.find('p').get_text()
Run Code Online (Sandbox Code Playgroud)

哪个打印:

College Type: 
Private Un-aided
Run Code Online (Sandbox Code Playgroud)

但我只想:

Private Un-aided
Run Code Online (Sandbox Code Playgroud)

位于立即<p>标记中 - 忽略子标记中的文本<strong>

python beautifulsoup

5
推荐指数
1
解决办法
1865
查看次数

Python:检查以扩展列表中存在的扩展名结尾的文件名

基本上我希望文件名以扩展名列表中的扩展名结尾.这是我在python中的代码.我已经将一些示例文件名作为列表,如下所示:

extensions = ['.mp3','.m4a','.wma']
filenames = ['foo1.mp3','foo2.txt','foo3.m4a','foo4.mp4']
for filename in filenames:
    for extension in extensions:
         if filename.endswith(extension):
             print filename
             break
Run Code Online (Sandbox Code Playgroud)

这是有效的,但我很想知道是否有更高效或简短的方法在python中做同样的事情.谢谢

python python-2.7

4
推荐指数
1
解决办法
1048
查看次数

Python:从第0个元素(元组中)中具有重复数据的元组列表中查找元组

我有一个包含文件名文件路径的元组列表.我想找到重复的文件名(但文件路径可能会有所不同),即元组,其文件名是相同的,但文件路径可能会有所不同.

元组列表的示例:

file_info = [('foo1.txt','/home/fold1'), ('foo2.txt','/home/fold2'), ('foo1.txt','/home/fold3')]
Run Code Online (Sandbox Code Playgroud)

我想找到重复的文件名,即file_info [2](在上面的例子中)打印并删除它.我可能会迭代检查:

count = 0
for (filename,filepath) in file_info:
    count = count + 1
    for (filename1,filepath1) in file_info[count:]:
        if filename == filename1:
            print filename1,filepath1
            file_info.remove((filename1,filepath1))
Run Code Online (Sandbox Code Playgroud)

但是,是否有更高效/更短/更正确/ pythonic的方式来完成相同的任务.谢谢.

python list python-2.7

2
推荐指数
1
解决办法
5760
查看次数

Python:将列表转换为字典,其中key是列表元素的索引

我有一个list,我想将它转换为一个字典dict,其中元素的键是列表中元素的位置:

>>> list_ = ['a', 'b', 'c', 'd']
>>> # I want the above list to be converted to a dict as shown below
...
>>> list_to_dict = {1: 'a',2: 'b', 3: 'c',4: 'd'}
Run Code Online (Sandbox Code Playgroud)

我知道这很简单,但有很多方法如下所示:

>>> {index+1: item for index, item in enumerate(list_)}
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
Run Code Online (Sandbox Code Playgroud)

我无法完全理解collections.defaultdict工作如何,我们可以用它来实现上述目标吗?或者也许还有其他更有效的方法?

python dictionary

1
推荐指数
1
解决办法
68
查看次数

标签 统计

python ×5

python-2.7 ×2

beautifulsoup ×1

dictionary ×1

list ×1

pandas ×1