繁体   English   中英

创建数据框,并为每个字符串的行显示在另一个数据框的列中

[英]Create Dataframe with rows made for each string appearing in a column of another 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

尝试这个

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM