Python将数据框架映射到字典

时间:2020-10-22 03:21:17

标签: python pandas dictionary

我有一个这样的字典

SingleChildScrollView(
child: Padding(
                  padding: const EdgeInsets.fromLTRB(20, 20, 0, 0),
                  child: Column(
                    children: [
                      Align(
                        alignment: Alignment.topLeft,
                        child: Text(
                            'Stories',
                            style: TextStyle(
                                color: Palette.white,
                                fontWeight: FontWeight.bold,
                                fontSize: 16
                            )
                        ),
                      ),
                      Stories(
                        currentUser: currentUser,
                        stories: stories,
                      ),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(0, 20, 0, 20),
                        child: RecommendedCards(),
                      ),
                      Expanded(
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: RecommendedFollowingList(
                              users: recommendedFollow
                          ),
                        )
                      ),
                      PolicyView()
                    ],
                  ),
                ),
              )

和数据框

dict={'1': 'AA',
 '2': 'GG',
 '3': 'AA',
 '4': 'CC',
 '5': 'TT',
 '6': 'AA',
 '7': 'TT',
 '8': 'GG',
 '9': 'CT',
 '10': 'AA',}

dict有100000个键和值,数据框有300行,例如,我只想打印数据框和dict之间重合的那一行。

df
VALUE RS TYPE CONDITION OTHER_COLUMN OTHER-COLUMN
SS 2 GG PROB 1 2
SS 2 GA INTER 1 2
SS 2 AA NORMAL 1 2
DD 9 CC PROB 1 2
DD 9 CT NORMAL 1 2
DD 9 TT INTER 1 2
FF 5 TT PROB 1 2
FF 5 TG INTER 1 2
FF 5 GG NORMAL 1 1

1 个答案:

答案 0 :(得分:0)

我将您的字典从dict重命名为mapper,因为dict是内置函数。如果字典将整数用作键,则可以摆脱.astype(str)

mapper={
 '1': 'AA',
 '2': 'GG',
 '3': 'AA',
 '4': 'CC',
 '5': 'TT',
 '6': 'AA',
 '7': 'TT',
 '8': 'GG',
 '9': 'CT',
 '10': 'AA'}

df[df.TYPE == df.RS.astype(str).map(mapper)]

出局:

  VALUE  RS TYPE CONDITION  OTHER_COLUMN  OTHER-COLUMN
0    SS   2   GG      PROB             1             2
4    DD   9   CT    NORMAL             1             2
6    FF   5   TT      PROB             1             2