Python问题中的数据科学导论

2024-10-06 09:30:00 发布

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

有人能告诉我那部分是什么吗thisLine.索引('(')-1])是吗?在

def get_list_of_university_towns():
'''Returns a DataFrame of towns and the states they are in from the 
university_towns.txt list. The format of the DataFrame should be:
DataFrame( [ ["Michigan", "Ann Arbor"], ["Michigan", "Yipsilanti"] ], 
columns=["State", "RegionName"]  )

The following cleaning needs to be done:
1. For "State", removing characters from "[" to the end.
2. For "RegionName", when applicable, removing every character from " (" to the end.
3. Depending on how you read the data, you may need to remove newline character '\n'. '''

data = []
state = None
state_towns = []
with open('university_towns.txt') as file:
    for line in file:
        thisLine = line[:-1]
        if thisLine[-6:] == '[edit]':
            state = thisLine[:-6]
            continue
        if '(' in line:
            town = thisLine[:thisLine.index('(')-1]
            state_towns.append([state,town])
        else:
            town = thisLine
            state_towns.append([state,town])
        data.append(thisLine)
df = pd.DataFrame(state_towns,columns = ['State','RegionName'])
return df

获取大学城的列表()


Tags: ofthetoinfromdataframedataline
2条回答

这一行执行已清理事物列表中要求2的部分:

例如:如果行是:

line = "Michigan, (Ann Arbor"

然后您的代码将输出Michigan,

它执行以下步骤:

2. For "RegionName", when applicable, removing every character from " (" to the end.

索引-1表示数组或列表的结尾。在

相关问题 更多 >