-1

我看到以下示例来说明如何在 DataFrame 中创建 NaN 列。

import pandas as pd
import numpy as np
import math
import copy
import datetime as dt

"""
Accepts a list of symbols along with start and end date
Returns the Event Matrix which is a pandas Datamatrix
Event matrix has the following structure :
    |IBM |GOOG|XOM |MSFT| GS | JP |
(d1)|nan |nan | 1  |nan |nan | 1  |
(d2)|nan | 1  |nan |nan |nan |nan |
(d3)| 1  |nan | 1  |nan | 1  |nan |
(d4)|nan |  1 |nan | 1  |nan |nan |
...................................
...................................
Also, d1 = start date
nan = no information about any event.
1 = status bit(positively confirms the event occurence)
"""

def find_events(ls_symbols, d_data):
    ''' Finding the event dataframe '''
    df_close = d_data['actual_close']
    ts_market = df_close['SPY']

    print "Finding Events"

    # Creating an empty dataframe
    df_events = copy.deepcopy(df_close) # type <class 'pandas.core.frame.DataFrame'>
    df_events = df_events * np.NAN # << why it works here

我尝试复制该方法如下:

import numpy as np
import pandas as pd
from pandas import Series, DataFrame

data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
        'year': [2000, 2001, 2002, 2001, 2002],
        'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
frame = DataFrame(data)
frame = frame * np.NAN # TypeError: can't multiply sequence by non-int of type 'float'

Q> 为什么它现在在这里不起作用?

4

2 回答 2

2

因为您有state包含字符串的列,并且将字符串与 a 相乘NaN会产生错误。如果您真的想将状态设置为NaN,请使用frame['state'] = np.NAN.

于 2013-03-22T17:04:37.270 回答
1

Notedf_close实际上是一个column,而不是一个数据框。(df_close = d_data['actual_close']。因此也是df_events)。您有一个包含三列的数据框,其中state是一个字符串,pandas 将其存储为 Python 对象。而且您不能将字符串/对象乘以数字。

无论如何,乘法是完全没有必要的:

  • 所做df_close = df_close * np.NaN的就是以不必要的混淆方式将 NaN 分配给整个 column
  • 直接赋值会清楚得多= np.NaN。或者pd.np.NaN
  • 如果要将 NaN 分配给多个列,请执行以下操作:df[['year','pop']] = pd.np.nan
  • 没有真正的乘法发生。只是不要写那样的代码。不要滥用运营商...
于 2019-12-14T06:22:45.487 回答