带有if/else和append函数的Python for循环 [英] Python for loop with if/else and append function

查看:164
本文介绍了带有if/else和append函数的Python for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据下面的列表,我必须创建一个带有状态"和区域"列的数据框:

On the basis of list as below, I have to create a DataFrame with "state" and "region" columns:

原始数据:

 Alabama[edit]
 Auburn (Auburn University)[1]
 Florence (University of North Alabama)
 Jacksonville (Jacksonville State University)[2]
 Livingston (University of West Alabama)[2]
 Montevallo (University of Montevallo)[2]
 Troy (Troy University)[2]
 Tuscaloosa (University of Alabama, Stillman College, Shelton State)[3][4]
 Tuskegee (Tuskegee University)[5]
 Alaska[edit]
 Fairbanks (University of Alaska Fairbanks)[2]
 Arizona[edit]
 Flagstaff (Northern Arizona University)[6]
 Tempe (Arizona State University)

(此处的数据链接. )

所需的输出:

State   Region
Alabama Auburn
Alabama Florence
Alabama Jacksonville
Alabama Livingston
Alabama Montevallo
Alabama Troy
Alabama Tuscaloosa
Alabama Tuskegee
Alaska  Fairbanks
Arizona Flagstaff
Arizona Tempe

代码:

    df = pd.DataFrame(columns=['State', 'RegionName'])
    with open('university_towns.txt', 'r') as UniversityList:
            content = UniversityList.readlines()
            state_row = []
            region_row = []
            for row in content:
                if '[edit]' in row:
                    state_row.append(row)
                    region_row.append('region_to_be_repeated')
                else:
                    region_row.append(row)
                    state_row.append('state_to_be_repeated')

在"if"为真"的情况下,如何将'state_to_be_reapeted'替换为附加内容?

How can I replace 'state_to_be_reapeted' with the content appended in case the "if" was True?

推荐答案

如果我理解您的问题并期望输出正确,则可以执行以下操作:

if I uderstand your question and desired output correct, you could do something like this:

univeristylist = []
with open('university_towns.txt', 'r') as file:
    for line in file:
        if '[edit]' in line:
            state = row
        else:
            universitylist.append([state, row])

df = pd.DataFrame(universitylist, columns=['State', 'RegionName'])

如果您不想使用'[edit]''[1]'部分,则可以将代码更改为:

If you don't want the '[edit]' and '[1]' part etc, then you could change the code to:

univeristylist = []
with open('university_towns.txt', 'r') as file:
    for line in file:
        if '[edit]' in line:
            state = row.split(' [')[0]
        else:
            universitylist.append([state, row.split(' [')[0]])

df = pd.DataFrame(columns=['State', 'RegionName'])

这篇关于带有if/else和append函数的Python for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆