使用为另一个Dataframe的列中显示的每个字符串创建的行创建Dataframe

时间:2017-10-24 18:19:17

标签: python pandas dataframe

如果您有如下数据框:

genre                 mean_average_budget
horror thriller       x
romance comedy        y 
action thriller       z
documentary           a
comedy documentary    b

如何制作行是类型列中每个字符串的各个外观? 例如:

genre                 mean_average_budget
horror                h
thriller              i 
action                k
documentary           l
comedy                m

1 个答案:

答案 0 :(得分:1)

试试这个

new_df = df.set_index('mean_average_budget').genre.str.split().\
    apply(pd.Series).stack().reset_index(1,drop = True).\
    reset_index(name = 'genre')

    mean_average_budget genre
0   x                   horror
1   x                   thriller
2   y                   romance
3   y                   comedy
4   z                   action
5   z                   thriller
6   a                   documentary
7   b                   comedy
8   b                   documentary

要查找均值,请尝试使用此数字数据

new_df.groupby('genre')['mean_average_budget'].mean()

如果你想聚合字符串

new_df.groupby('genre')['mean_average_budget'].apply('+'.join)