Python for loop with if/else and append function

后端 未结 3 755
别那么骄傲
别那么骄傲 2021-01-21 18:26

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

Original data:

 Alabama[edit]
 Auburn (Auburn Universi         


        
3条回答
  •  失恋的感觉
    2021-01-21 18:56

    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'])
    

    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'])
    

提交回复
热议问题