【问题标题】:Create a column based on another dataframe values根据另一个数据框值创建列
【发布时间】:2015-11-02 04:47:35
【问题描述】:
import pandas as pd
import io
import numpy as np
import datetime

data = """
    date          id
    2015-10-31    50230
    2015-10-31    48646
    2015-10-31    48748
    2015-10-31    46992
    2015-11-01    46491
    2015-11-01    45347
    2015-11-01    45681
    2015-11-01    46430
    """

df = pd.read_csv(io.StringIO(data), delimiter='\s+', index_col=False, parse_dates = ['date'])

df2 = pd.DataFrame(index=df.index)

df2['Check'] = np.where(datetime.datetime.strftime(df['date'],'%B')=='October',0,1)

我正在使用这个示例。 df2['Check'] 所做的是如果 df['date'] == 'October' 则分配 0,否则分配 1。

np.where 在其他条件下工作正常,但strftime 不喜欢导致此错误的系列:

Traceback (most recent call last):
  File "C:/Users/Leb/Desktop/Python/test2.py", line 22, in <module>
    df2['Check'] = np.where(datetime.datetime.strftime(df['date'],'%B')=='October',0,1)
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'Series'

如果我循环使用大约 1M 的实际数据需要很长时间。我怎样才能有效地做到这一点?

df2['Check'] 应如下所示:

  Check
0     0
1     0
2     0
3     0
4     1
5     1
6     1
7     1

【问题讨论】:

  • 使用.dt 访问器。使用熊猫 0.17。请参阅docs。您收到错误是因为 datetime 使用单个参数,而不是数组。
  • 非常有用,我会记住这一点。我现在有 0.16 的 anaconda 的一部分。
  • 不应该 df['date'].dt.month==9 即使在 0.16.0 中也能工作?

标签: python datetime numpy pandas dataframe


【解决方案1】:

这是一个稍微简单的版本,使用datetime 对象的month 属性。如果等于 10,只需将 true / false 值映射到所需的 0 / 1 对:

df2['Check']=df.date.apply(lambda x: x.month==10).map({True:0,False:1})

【讨论】:

    【解决方案2】:

    @ako 的答案是钱,但基于 @Kartik 和 @EdChum 的 cmets,这是我想出的:

    import pandas as pd
    import io
    import numpy as np
    
    data = """
        2015-10-31    50230
        2015-10-31    48646
        2015-10-31    48748
        2015-10-31    46992
        2015-11-01    46491
        2015-11-01    45347
        2015-11-01    45681
        2015-11-01    46430
        """
    
    df = pd.read_csv(io.StringIO(data*125000), delimiter='\s+', index_col=False, names=['date','id'], parse_dates = ['date'])
    
    df2 = pd.DataFrame(index=df.index)
    
    df.shape
    (1125000, 2)
    
    %timeit df2['Check']=df.date.apply(lambda x: x.month==10).map({True:0,False:1})
    1 loops, best of 3: 2.56 s per loop
    
    %timeit df2['date'] = np.where(df['date'].dt.month==10,0,1)
    10 loops, best of 3: 80.5 ms per loop
    

    【讨论】:

      猜你喜欢
      • 2023-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-23
      • 2020-04-11
      • 2020-12-10
      • 2020-02-23
      相关资源
      最近更新 更多