我在想:
1.)如何在列中查找特定字符串
2.)给定该字符串,如何找到它对应的max
3.)如何计算该列中每行的字符串数
我有一个csv文件叫做体育.csv你知道吗
import pandas as pd
import numpy as np
#loading the data into data frame
X = pd.read_csv('sports.csv')
感兴趣的两列是Totals
和Gym
列:
Total Gym
40 Football|Baseball|Hockey|Running|Basketball|Swimming|Cycling|Volleyball|Tennis|Ballet
37 Baseball|Tennis
61 Basketball|Baseball|Ballet
12 Swimming|Ballet|Cycling|Basketball|Volleyball|Hockey|Running|Tennis|Baseball|Football
78 Swimming|Basketball
29 Baseball|Tennis|Ballet|Cycling|Basketball|Football|Volleyball|Swimming
31 Tennis
54 Tennis|Football|Ballet|Cycling|Running|Swimming|Baseball|Basketball|Volleyball
33 Baseball|Hockey|Swimming|Cycling
17 Football|Hockey|Volleyball
请注意,Gym
列中有多个对应运动的字符串,我试图找到一种方法来查找所有有棒球的健身房,并找到总数最大的一个。不过,我只对至少有两项其他运动的健身房感兴趣,即我不想考虑:
Total Gym
37 Baseball|Tennis
您可以在读取文件时一次性完成:
这会给你:
另一种不拆分的方法是计算管道字符:
这意味着尽管一个子串可能与一个确切的词相匹配。你知道吗
您可以使用
pandas
轻松地做到这一点首先,在制表符分隔符上将字符串拆分为一个列表,然后遍历该列表并选择长度大于2的字符串,因为您希望棒球和其他两项运动作为标准。你知道吗
使用
str.contains
在Gym
列中搜索字符串Baseball
。你知道吗计算各自的字符串计数。你知道吗
然后选择与
Totals
列中的最大值对应的数据帧子集。你知道吗试试这个:
相关问题 更多 >
编程相关推荐