简体   繁体   English

Python 循环遍历 DataFrame 和字典

[英]Python Looping through DataFrame and Dictionary

I have one data frame that looks like the below我有一个如下所示的数据框

0   1   2
A   X   +2
B   Y   +3
C   Z   +1+2

And a dictionary that looks like the below还有一个看起来像下面的字典

    dict = { "1":"A", "2":"B", "3":"C", }

I am trying to loop through to create the below (effectively looking up the letter from the dictionary and replacing the number in the data frame with the correct letter while keeping the "+"s )我正在尝试循环创建以下内容(有效地从字典中查找字母并用正确的字母替换数据框中的数字,同时保留“+”s)

    0   1   2
    A   X   +B
    B   Y   +C
    C   Z   +A+B

Any pointers would be much appreciated!任何指针将不胜感激!

You could use replace :您可以使用替换

import pandas as pd

d = {"1": "A", "2": "B", "3": "C", }

data = [['A',  'X', '+2'],
        ['B',  'Y', '+3'],
        ['C',  'Z', '+1+2']]

df = pd.DataFrame(data=data)

df[2] = df[2].str.replace('\d+', lambda x: d[x.group()])

print(df)

Output Output

   0  1     2
0  A  X    +B
1  B  Y    +C
2  C  Z  +A+B

You can split and join on the + character (below is where the dictionary variable is d ):您可以在+字符上拆分和加入(下面是字典变量d的位置):

df['2'] = df['2'].apply(lambda s: '+'.join(d.get(n, "") 
                                           for n in s.split('+')))
>>> df
   0  1     2
0  A  X    +B
1  B  Y    +C
2  C  Z  +A+B

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM