用于处理行和列的数据结构

2024-10-04 07:29:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我将数据以表格形式抓取到Python中:

Name  Sport   Score  
John  Golf    100
Jill  Rugby   55
John  Hockey  100
Bob   Golf    45

如何在Python中格式化这个表,以便对项目进行排序或分组。例如,如果我想看到所有打高尔夫球的人的名字,或者所有在任何运动中得分100的人的名字。或者只是约翰的所有数据。你知道吗


Tags: 数据项目name排序名字john形式表格
3条回答

pandas'DataFrame将是一条道路:

import pandas as pd

df = pd.DataFrame({'Name': ['John', 'Jill', 'John', 'Bob'], 
                   'Sport' : ['Golf', 'Rugby', 'Hockey', 'Golf'],
                   'Score': [100, 50, 100, 45]}) 

# the names of people that played Golf

df[df['Sport'] == 'Golf']['Name'].unique()
>> ['John' 'Bob']

# all of the people that scored 100 on any sport.

df[df['Score'] == 100]['Name'].unique()
>> ['John']

# all of the data for just John.
df[df['Name'] == 'John']
>>    Name  Score   Sport
   0  John    100    Golf
   2  John    100  Hockey

这个怎么样?你知道吗

yourDS={"name":["John","Jill","John","Bob"],
    "sport":["Golf","Rugby","Hockey","Golf"],
    "score":[100,55,100,45]
}

这应该保持列表排序时每个条目的关系。你知道吗

为了避免列表中重复元素的影响,首先从列表中创建一个新的set。你知道吗

对于预期的查询,可以这样做。你知道吗

for index,value in enumerate(yourDS["score"]):
    if value=="x":
        print yourDS["name"][index] 

最好使用list来存储结果,并使其成为set,以避免某些情况,例如,如果一个人在两个不同的游戏中得分为x。你知道吗

带有namedtuplelambdamapfilter可用于此任务。你知道吗

from collections import namedtuple

# Create a named tuple to store the rows
Row = namedtuple('Row', ('name', 'sport', 'score'))

data = '''Name  Sport   Score  
          John  Golf    100
          Jill  Rugby   55
          John  Hockey  100
          Bob   Golf    45'''

# Read the data, skip the first line
lines = data.splitlines()[1:]
rows = []
for line in lines:
    name, sport, score = line.strip().split()
    rows.append(Row(name, sport, int(score)))

# People that played Golf
golf_filter = lambda row: row.sport == 'Golf'
golf_players = filter(golf_filter, rows)

# People that scored 100 on any sport
score_filter = lambda row: row.score == 100
scorers = filter(score_filter, rows)

# People named John
john_filter = lambda row: row.name == 'John'
john_data = filter(john_filter, rows)

# If you want a specific column than you can map the data
# Names of golf players
get_name = lambda row: row.name
golf_players_names = map(get_name, golf_players)

结果:

>>> golf_players
[Row(name='John', sport='Golf', score=100),
 Row(name='Bob', sport='Golf', score=45)]

>>> john_data
[Row(name='John', sport='Golf', score=100),
 Row(name='John', sport='Hockey', score=100)]

>>> scorers
[Row(name='John', sport='Golf', score=100),
 Row(name='John', sport='Hockey', score=100)]

>>> golf_players_names
['John', 'Bob']

相关问题 更多 >