Python 熊猫申请及;映射到每列的每个元素

Python 熊猫申请及;映射到每列的每个元素,python,python-2.7,pandas,pandas-apply,Python,Python 2.7,Pandas,Pandas Apply,如果自定义函数的值不为null,如何将其应用于每列的每个元素 假设我有一个10列的数据帧,其中我想对每一个只有4列的元素应用一个lower()函数,如果pd.notnull(x),否则只保留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

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

假设我有一个10列的数据帧,其中我想对每一个只有4列的元素应用一个lower()函数,如果pd.notnull(x),否则只保留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为float,rest为unicode)。这给我带来了一个错误-

float has no attribute map.

如何消除此错误?

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

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

这项工作:

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
我认为您需要,因为工作要素方面:

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

非常感谢。这是有道理的。如何仅对数据框中的某些列应用此选项?