python - 用基于字典的条目数组替换 Pandas DataFrame 列中的字符串

标签 python arrays pandas dictionary

我有一个数据框,例如:

     tag1   other
0    a,c      foo
1    b,c      foo
2    d        foo
3    a,a      foo

其中条目是由逗号分隔的字符串。

以及每个标签的定义字典,例如:

dict = {'a' : 'Apple',
'b' : 'Banana',
'c' : 'Carrot'}

我想替换 abc 的定义,但删除那些不在该字典中的行(即 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

最佳答案

为了我进入最长的单类轮比赛

m = {
    'a' : 'Apple',
    'b' : 'Banana',
    'c' : 'Carrot'
}

df.tag1.str.split(',', expand=True) \ 
  .stack().map(m).groupby(level=0) \
  .filter(lambda x: x.notnull().all()) \
  .groupby(level=0).apply(lambda x: x.drop_duplicates().str.cat(sep=',')) \
  .to_frame('tag1').join(df.other)

            tag1 other
0   Apple,Carrot   foo
1  Banana,Carrot   foo
3          Apple   foo

但说真的,可能是更好的解决方案

a = np.core.defchararray.split(df.tag1.values.astype(str), ',')
lens = [len(s) for s in a]
b = np.concatenate(a)
c = [m.get(k, np.nan) for k in b]
i = df.index.values.repeat(lens)
s = pd.Series(c, i)

def proc(x):
    if x.notnull().all():
        return x.drop_duplicates().str.cat(sep=',')

s.groupby(level=0).apply(proc).dropna().to_frame('tag1').join(df.other)

            tag1 other
0   Apple,Carrot   foo
1  Banana,Carrot   foo
3          Apple   foo

关于python - 用基于字典的条目数组替换 Pandas DataFrame 列中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44293358/

相关文章:

python - 我在学习 python 类(class)时无法理解一段代码是什么

python - 获取没有 XPath 的 WebElement 的兄弟元素 [Python/Selenium]

python - Pandas Python 中的共享 x 轴

java - 在线性 (O(N)) 时间内对数组进行排序

python - 如何从转置格式将 .txt 文件读入 pandas DataFrame

python-3.x - Pandas:使用 DataFrameGroupBy.filter() 方法选择 DataFrame 中值大于相应组平均值的行

Python:将 nDimensions 列表转换为字符串,反之亦然

python - 在 Windows bash 上 pip install flask 不起作用

arrays - 扩展 bash 数组只给出第一个元素

python - 我如何在 numpy 中做这个数组索引