Split strings in tuples into columns, in Pandas

前端 未结 3 2114
梦如初夏
梦如初夏 2020-12-03 02:43

I have the following DataFrame, where Track ID is the row index. How can I split the string in the stats column into 5 columns of numb

3条回答
  •  半阙折子戏
    2020-12-03 03:15

    Assuming you have a column which contains tuples (as it appears in your example) rather than strings, this will work:

    df = pandas.DataFrame({'Track ID': [14, 28, 42], 'stats': [(1, 2, 3, 4, 5), (1, 2, 3, 4, 5), (1, 2, 3, 4, 5)]}).set_index("Track ID")
    
    from operator import itemgetter
    for i in range(5):
        df["Col {}".format(i)] = df.stats.apply(itemgetter(i))
    

    If you actually have strings that look like tuples, you can parse them first and then apply the same pattern as above:

    df = df2 = pandas.DataFrame({'Track ID': [14, 28, 42], 'stats': ["(1, 2, 3, 4, 5)", "(1, 2, 3, 4, 5)", "(1, 2, 3, 4, 5)"]}).set_index("Track ID")
    df.stats = df2.stats.str.strip("()").str.split(", ")
    

提交回复
热议问题