Fel*_*ang 3 python dataframe python-3.x pandas
循环遍历带有字符串的数据帧的最佳方法是什么,我想将其拆分为多行同时保留另一个值?
输入:
genres revenue
action|comedy|drama 5000
action|romance 10000
Run Code Online (Sandbox Code Playgroud)
输出:
genres revenue
action 5000
comedy 5000
drama 5000
action 10000
romance 10000
Run Code Online (Sandbox Code Playgroud)
使用Series.str.split与分配回柱DataFrame.assign和DataFrame.explode,最后默认索引添加DataFrame.reset_index有drop=True:
df1=df.assign(genres = df['genres'].str.split('|')).explode('genres').reset_index(drop=True)
print (df1)
genres revenue
0 action 5000
1 comedy 5000
2 drama 5000
3 action 10000
4 romance 10000
Run Code Online (Sandbox Code Playgroud)