如何使用 .loc 将函数应用于列切片?

Max*_*kov 5 python apply dataframe pandas

我有一个整数显示为字符串的 pd DataFrame:

frame = pd.DataFrame(np.random.randn(4, 3), columns=list('ABC'), index=['1', '2', '3', '4'])
frame = frame.apply(lambda x: x.astype(str))
Run Code Online (Sandbox Code Playgroud)

这给了我一个数据框:

     A      B      C
1 -0.890  0.162  0.477
2 -1.403  0.160 -0.570
3 -1.062 -0.577 -0.370
4  1.142  0.072 -1.732
Run Code Online (Sandbox Code Playgroud)

如果我输入 frame.type() 我会得到对象。现在我想将列 ['B':'C'] 转换为数字。

想象一下,我有几十列,因此我想对它们进行切片。所以我要做的是:

frame.loc[:,'B':'C'] = frame.loc[:,'B':'C'].apply(lambda x: pd.to_numeric(x, errors='coerce')
Run Code Online (Sandbox Code Playgroud)

如果我只是想改变列,比如 B,我会输入:

frame['B'] = frame['B'].apply(lambda x: pd.to_numeric(x, errors='coerce')
Run Code Online (Sandbox Code Playgroud)

这会将 B 转换为 float64 但是如果我将它与 .loc 一起使用,那么在我调用 DataFrame.info() 之后什么也没有发生!

有人能帮我吗?当然,我可以只输入所有列,但我想获得更实用的方法

piR*_*red 8

您可以将 kwargs 传递给 apply

符合 assign

frame.assign(**frame.loc[:, 'B':'C'].apply(pd.to_numeric, errors='coerce'))

                 A         B         C
1   -1.50629471392 -0.578600  1.651437
2   -2.42667924339 -0.428913  1.265936
3  -0.866740402265 -0.678886 -0.094709
4    1.49138962612 -0.638902 -0.443982
Run Code Online (Sandbox Code Playgroud)

update

frame.update(frame.loc[:, 'B':'C'].apply(pd.to_numeric, errors='coerce'))
frame

                 A         B         C
1   -1.50629471392 -0.578600  1.651437
2   -2.42667924339 -0.428913  1.265936
3  -0.866740402265 -0.678886 -0.094709
4    1.49138962612 -0.638902 -0.443982
Run Code Online (Sandbox Code Playgroud)


Max*_*axU 5

您可以按如下方式生成列列表:

In [96]: cols = frame.columns.to_series().loc['B':'C'].tolist()
Run Code Online (Sandbox Code Playgroud)

并使用此变量来选择“感兴趣的列”:

In [97]: frame[cols] = frame[cols].apply(lambda x: pd.to_numeric(x, errors='coerce'))

In [98]: frame.dtypes
Out[98]:
A     object
B    float64
C    float64
dtype: object
Run Code Online (Sandbox Code Playgroud)