我正在尝试从数据框中的 gen
列中提取项目(下面的示例)。我的目标是将 gen
中的每一行迭代到一个新的数据框列中,其中的项目与预定义列表 genre_code
匹配。
df = pd.DataFrame({'id': [620, 843, 986], 'tit': ['AAA', 'BBB', 'CCC'], 'gen': [['Romance', 'Satire', 'Fiction'], ['Science Fiction', 'Novel'], ['Mystery', 'Novel']]})
genre_code = ['Science Fiction', 'Mystery', 'Non-fiction']
到目前为止,我能够得出以下结论:
new_gen = []
for i in df['gen']:
for j in i:
if j in genre_code:
new_gen.append(j)
else:
new_gen.append('NA')
df['gen'] = new_gen
它确实遍历列,但生成的 new_gen
的长度与原始数据帧行长度不匹配。
/usr/local/lib/python3.7/dist-packages/pandas/core/internals/construction.py in sanitize_index(data, index)
746 if len(data) != len(index):
747 raise ValueError(
--> 748 "Length of values "
749 f"({len(data)}) "
750 "does not match length of index "
ValueError: Length of values (30004) does not match length of index (12841)
我知道这一定是一些非常基本的东西,但是有人可以指出我遗漏了什么吗?
最佳答案
如果你想根据你的列表过滤 gen
列,你可以这样做:
df["gen"] = df["gen"].apply(lambda x: [g for g in x if g in genre_code])
print(df)
打印:
id tit gen
0 620 AAA []
1 843 BBB [Science Fiction]
2 986 CCC [Mystery]
P.S: 为了加快这个过程,你可以将 genre_code
转换为 set()
之前:
genre_code = set(["Science Fiction", "Mystery", "Non-fiction"])
df["gen"] = df["gen"].apply(lambda x: [g for g in x if g in genre_code])
关于python - 遍历嵌套的字符串列表以获取第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66942429/