我有带电影标题的数据帧和带流派的专栏。例如标题为“One”的电影是“Action”和“Vestern”,因为在适当的列中有“1”。你知道吗
Movie Action Fantasy Vestern
0 One 1 0 1
1 Two 0 0 1
2 Three 1 1 0
我的目标是创建genres
列,它将包含特定电影的每种类型的名称。
为此,我尝试使用lambda
和list comprehension
,因为我认为这有帮助。但在运行了这样一行代码之后:
df['genres'] = df.apply(lambda x: [x+"|"+x for x in df.columns if x!=0])
我在每行中只得到NaN
值:
Movie Action Fantasy Vestern genres
0 One 1 0 1 NaN
1 Two 0 0 1 NaN
2 Three 1 1 0 NaN
也尝试使用groupby
,但没有成功。你知道吗
预期输出为:
Movie Action Fantasy Vestern genres
0 One 1 0 1 Action|Vestern
1 Two 0 0 1 Vestern
2 Three 1 1 0 Action|Fantasy
要复制的代码:
import pandas as pd
import numpy as np
df = pd.DataFrame({"Movie":['One','Two','Three'],
"Action":[1,0,1],
"Fantasy":[0,0,1],
"Vestern":[1,1,0]})
print(df)
谢谢你的帮助
输出
为了提高性能,可以使用^{} 所有不带第一个的列,所有不带最后一个的列,最后一个通过^{} 删除最后一个
|
:或者使用列表理解来连接所有没有空字符串的值:
性能:
相关问题 更多 >
编程相关推荐