【发布时间】:2021-06-30 16:33:16
【问题描述】:
我正在尝试从数据框中的 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)
我知道这一定是非常基本的东西,但有人可以指出我缺少什么吗?
【问题讨论】:
标签: python pandas loops nested-lists