Python, Pandas数据框:为什么我不能直接将数据指定给df.values = df.values / 100?

2024-05-23 16:51:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想去 1) 从FamaFrench网站读取数据 2) 将日期(月、年)转换为DateTime对象 3) 将所有退货数据转换为百分比退货(退货/100)

我下面的代码读取famafrench网站的数据。你知道吗

industry30Web =web.DataReader("30_Industry_Portfolios","famafrench")
industry30_monthlyVal = industry30Web[4]
dateInt = industry30_monthlyVal.index
conv = lambda x: datetime.datetime.strptime(str(x),'%Y%m')
dates = [conv(x) for x in dateInt]
industry30_monthlyVal.index =  dates
industry30_monthlyVal.values = industry30_monthlyVal.values/100 

最后一行显示AttributeError

请帮帮我,让我知道我做错了什么。你知道吗


Tags: 数据datetimeindex网站dateint读取数据datesvalues
2条回答

documentation明确地指出,您不能分配给values属性。你知道吗

但是,您可以通过执行industry30_monthlyVal[:]= industry30_monthlyVal[:]/100来实现您想要的

当我在generic下查看源代码时pd.数据帧我发现:

@property
def values(self):
    """Numpy representation of NDFrame

    Notes
      -
    The dtype will be a lower-common-denominator dtype (implicit
    upcasting); that is to say if the dtypes (even of numeric types)
    are mixed, the one that accommodates all will be chosen. Use this
    with care if you are not dealing with the blocks.

    e.g. If the dtypes are float16 and float32, dtype will be upcast to
    float32.  If dtypes are int32 and uint8, dtype will be upcase to
    int32.
    """
    return self.as_matrix()

该方法不能将数据写入数据帧(例如,可以覆盖的类变量)。 apply功能可能就是您想要的:

import numpy as np, pandas as pd
s = pd.dataFrame(np.random.randn(10))
s = s.apply(lambda x: x/100)

它对数据帧的工作方式相同

相关问题 更多 >