【发布时间】:2017-11-01 18:22:14
【问题描述】:
我有一个 DataFrame,例如:
tag1 other
0 a,c foo
1 b,c foo
2 d foo
3 a,a foo
其中的条目是用逗号分隔的字符串。
以及每个标签的定义字典,例如:
dict = {'a' : 'Apple',
'b' : 'Banana',
'c' : 'Carrot'}
我想替换a、b 和c 的定义,但删除该字典中没有内容的行(即d)。此外,我想确保没有重复,例如示例数据集中的行索引 3。
到目前为止我所拥有的:
df.tags = df.tags.str.split(',')
for index, row in df.iterrows():
names = []
for tag in row.tag1:
if tag == dict[tag]:
names.append(dict[tag])
else:
df.drop(df.index[index])
从那里我将用names 中的值替换原始列。为了替换重复项,我正在考虑遍历数组并检查下一个值是否与下一个匹配,如果是,则删除它。但是,这不起作用,我有点难过。所需的输出看起来像(使用 unicode 字符串):
tag1 other
0 ['Apple', 'Carrot'] foo
1 ['Banadn', 'Carrot'] foo
3 ['Apple'] foo
【问题讨论】:
-
想要的输出是什么样的?
-
我已经编辑了,谢谢。
标签: python arrays pandas dictionary