【问题标题】:the .map() method is not mapping all the values of the dictionary in a dataframe column. Is there a way around this?.map() 方法没有将字典的所有值映射到数据框列中。有没有解决的办法?
【发布时间】:2020-08-29 15:44:22
【问题描述】:

我准备了一个字典,键为 1 到 10,每个对应一种颜色。我想将此字典映射到数据框列中的相应值。

字典看起来像这样:

color_dict = {'1':'white' ,'2':'black' ,'3':'brown' ,'4':'red' ,'5':'orange' ,'6':'yellow' ,'7':'green' ,'8':'blue' ,'9':'purple' ,'10':'grey'}

我试图将此字典映射到的列如下所示:

col_happy.head()

original column 这些值对应于 color_dict 字典中标记的颜色。

应用pandas 的.map() 后,我得到如下输出: output 不知何故,映射函数并未将所有值映射到列中。如何解决?

【问题讨论】:

  • 您的专栏是否包含字符串或数字? IE。是6 还是'6'?因为您在 dict 中使用字符串作为键,但我认为您在数据框中混合使用了字符串和数字。
  • 数据类型为对象。该怎么办?

标签: python pandas dictionary


【解决方案1】:

试试这个:

df = pd.DataFrame(color_dict.items())
print(df)

输出:

0       1
0   1   white
1   2   black
2   3   brown
3   4     red
4   5  orange
5   6  yellow
6   7   green
7   8    blue
8   9  purple
9  10    grey

【讨论】:

    【解决方案2】:

    好吧,不确定这些值是str 还是int,所以你可以修改字典以同时拥有两者 -

    color_dict = {'1':'white',  1:'white',
                  '2':'black',  2:'black',
                  '3':'brown',  3:'brown',
                  '4':'red',    4:'red',
                  '5':'orange', 5:'orange',
                  '6':'yellow', 6:'yellow',
                  '7':'green',  7:'green',
                  '8':'blue',   8:'blue',
                  '9':'purple', 9:'purple',
                  '10':'grey',  10:'grey'}
    

    如果您的数据框如图所示-

       0
    0  4
    1  6
    2  7
    3  9
    4  2
    

    然后这样做 -

    # Again the column name can also be 0: int, '0': str
    # so using iloc instead
    
    df.iloc[:,0] = df.iloc[:,0].map(color_dict)
    

    输出-

    0       red
    1    yellow
    2     green
    3    purple
    4     black
    

    【讨论】:

    • 这并没有完全给我结果。它生成的输出与我之前作为图像共享的输出相同。我很确定这些值是字符串值......如果我使用 .replace() 输出也不会完全改变......它只是保持数字不变
    • 怎么样:df.iloc[:,0] = df.iloc[:,0].map(str).map(color_dict)
    • 试试这个:df.iloc[,:0].apply(int) 将整列更改为 int,因为“1”将变为 1,“1”也将变为 1
    猜你喜欢
    • 2021-06-03
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    相关资源
    最近更新 更多