【问题标题】:Pandas apply & map to every element of every columnPandas 应用并映射到每一列的每个元素
【发布时间】:2017-11-17 08:04:38
【问题描述】:

如果每个列的值不为空,如何将自定义函数应用于每个列的每个元素?

假设我有一个包含 10 列的数据框,如果是 pd.notnull(x),我想将 lower() 函数应用于仅 4 列的每个元素,否则只保留 none 作为值。

我试过这样用,

s.apply(lambda x: change_to_lowercase(x), axis = 1)

def change_to_lowercase(s):

    s['A'] =  s['A'].map(lambda x: x.lower() if pd.notnull(x) else x)
    s['B'] = s['B'].map(lambda x: x.lower() if pd.notnull(x) else x)
    s['C'] = s['C'].map(lambda x: x.lower() if pd.notnull(x) else x)
    s['D'] = s['D'].map(lambda x: x.lower() if pd.notnull(x) else x)
    return s

但由于我的列是混合数据类型(NaN 为浮点数,其余为 unicode)。这给我一个错误-

float has no attribute map.

如何摆脱这个错误?

【问题讨论】:

    标签: python python-2.7 pandas pandas-apply


    【解决方案1】:

    您正在尝试映射一个系列,然后在 lambda 中获取整行。

    您还应该检查没有方法 .lower() 的整数、浮点数等。所以在我看来,最好是检查它是否是一个字符串,而不仅仅是它是否不是一个非空值。

    这行得通:

    s = pd.DataFrame([{'A': 1.5, 'B':"Test", 'C': np.nan, 'D':2}])
    s
    
            A   B   C   D
    0   1.5 Test    NaN 2
    
    
    
    s1 = s.apply(lambda x: x[0].lower() if isinstance(x[0], basestring) else x[0]).copy()
    
    s1
        A     1.5
        B    test
        C     NaN
        D       2
        dtype: object
    

    让python 3检查字符串isinstance(x[0], str)

    为了能够选择列:

    s1 = pd.DataFrame()
    columns = ["A", "B"]
    for column in columns:
        s1[column] = s[column].apply(lambda x: x.lower() if isinstance(x, str) else x).copy()
    s1
    
        A   B
    0   1.5 test
    

    【讨论】:

    • 谢谢。这就说得通了。如何仅将其应用于数据框中的某些列?
    【解决方案2】:

    我认为您需要 DataFrame.applymap 因为按元素工作:

    L = [[1.5, 'Test', np.nan, 2], ['Test', np.nan, 2,'TEST'], ['Test', np.nan,1.5,  2]]
    df = pd.DataFrame(L, columns=list('abcd'))
    print (df)
    
          a     b    c     d
    0   1.5  Test  NaN     2
    1  Test   NaN  2.0  TEST
    2  Test   NaN  1.5     2
    
    cols = ['a','b']
    #for python 2 change str to basestring
    df[cols] = df[cols].applymap(lambda x: x.lower() if isinstance(x, str) else x)
    print (df)
          a     b    c     d
    0   1.5  test  NaN     2
    1  test   NaN  2.0  TEST
    2  test   NaN  1.5     2
    

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      相关资源
      最近更新 更多