【问题标题】:How to apply function to slice of columns using .loc?如何使用 .loc 将函数应用于列切片?
【发布时间】:2018-09-07 08:59:03
【问题描述】:

我有一个 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))

这给了我一个数据框:

     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

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

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

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

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

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

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

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

【问题讨论】:

标签: python pandas dataframe apply


【解决方案1】:

您可以将 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

使用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

【讨论】:

  • 亲爱的 piRsquared,非常感谢!以下代码对我有用: frame = frame.assign(**frame.loc[:, 'B':'C'].apply(pd.to_numeric, errors='coerce'))
  • 第二种更新方法对我不起作用。可能是因为 this issue 关于 df.update 不保存 dtypes
【解决方案2】:

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

In [96]: cols = frame.columns.to_series().loc['B':'C'].tolist()

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

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

【讨论】:

    猜你喜欢
    • 2020-11-25
    • 2017-07-27
    • 1970-01-01
    • 2020-05-07
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    相关资源
    最近更新 更多