Pandas: Efficient way of creating new column based on other column. Many to few

时间:2016-02-12 20:13:05

标签: python-2.7 dictionary pandas apply

For example:

df = pd.DataFrame( {"A": [7001, 8001, 9001]} )
equiv = {1:[7001, 8001], 2: [9001]}
df["B"] = df["A"].map(equiv.get)

to end up with

a, b
7001, 1
8001, 1
9001, 2

I was thinking something like:

df = pd.DataFrame( {"A": [7001, 8001, 9001]} )
equiv = {1:[7001, 8001], 2: 9001}
df["B"] = df["A"].map(equiv.get)

I do not want to use equiv = {7001:1, 8001:1, 9001:2} because in my actual dataset I will have many string values that map to 1 and 2

1 个答案:

答案 0 :(得分:1)

You can use Install-Package Tesseract -Version 2.4.1 and then map it:

inverted dictionary