熊猫:使用超过1列的dict映射

时间:2017-11-14 09:29:12

标签: python-3.x pandas python-applymap

我有基本的DataFrame:

df = pd.DataFrame([[1, 2],[3, 4],[5, 6],[7, 8]],
                  index=['A','B','C','D'], columns=['X','Y'])

我希望map函数能够用于X和X列。 Y并获得此:

   X  Y  Chk
A  1  2  found A
B  3  4  found B
C  5  6  found C
D  7  8  found D

为此,我为2个键创建了一个dict:

mapped = {1:{2:'found A'}, 3:{4:'found B'},5:{6:'found C'}, 7:{8:'found D'}}

在DataFrame上使用了applymap方法:

df['Chk'] = df[['X','Y']].applymap(mapped)

不幸的是,我收到了一条错误消息:

TypeError: ("'dict' object is not callable", 'occurred at index X')

代码是错误的,还是基于dict的映射只是不支持超过1列?

1 个答案:

答案 0 :(得分:1)

首先Data.ByteString.Char8 first sentence HttpClient httpClient = new DefaultHttpClient(); try { HttpPost request = new HttpPost("http://xxx.xxx.com/fashionnewssignup"); StringEntity params =new StringEntity("{\"fashionSignups\":[{\"corporateBrandId\":0,\"vendorId\":null,\"countryCode\":\"pt\",\"languageCode\":\"pt\",\"email\":\"test@ytDessddefwwt.com\",\"genderCode\":0,\"hasChildren\":0,\"zipcode\":\"12345\"}]}"); request.addHeader("content-type", "application/json"); request.setEntity(params); HttpResponse response = httpClient.execute(request); String s = response.getStatusLine()+" " + response.toString(); System.out.println(s); }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown(); } DataFrame再创建Series,然后stack再创建MultiIndex

s = pd.DataFrame(mapped).stack().rename('Chk')
print (s)
2  1    found A
4  3    found B
6  5    found C
8  7    found D
Name: Chk, dtype: object

df = df.join(s, on=['Y','X'])
print (df)
   X  Y      Chk
A  1  2  found A
B  3  4  found B
C  5  6  found C
D  7  8  found D

如果可能,请创建DataFrame进行制图,然后使用join

mapped = {'X': [1, 3, 5, 7], 
         'Chk': ['found A', 'found B', 'found C', 'found D'],
         'Y': [2, 4, 6, 8]}

df1 = pd.DataFrame(mapped)
print (df1)
       Chk  X  Y
0  found A  1  2
1  found B  3  4
2  found C  5  6
3  found D  7  8

df = pd.merge(df, df1, how='left', on=['X','Y'])
print (df)
   X  Y      Chk
0  1  2  found A
1  3  4  found B
2  5  6  found C
3  7  8  found D