【问题标题】:'Timestamp' object is not iterable“时间戳”对象不可迭代
【发布时间】:2017-09-28 05:55:00
【问题描述】:

我正在尝试将 pandas.core.series.Series (df1['col1']) 与 pandas.core.frame.DataFrame (df2) 相乘。它们的索引是相同的,但当我试图通过做来乘以它们时,它总是让我返回“''Timestamp' object is not iterable'”

k = df1['col1'].mul(df2)


[In] df1:
[out]
Index         col1    col2
2065-12-20     12      apples
2061-10-31     12      candies
2045-11-28     70      marshmalow
2043-10-31     11      apples
2040-07-30     21      cars
2049-06-30     64      planes
2036-01-31     14      glasses



[In] df2: 
Index             col1    col2   etc.... 
2065-12-20         14      120
2061-10-31         18      800
2045-11-28         19      580
2043-10-31         21      12
2040-07-30         44      21
2049-06-30         1.2     17
2036-01-31         61.8    61 

我想要

Index             col1        col2   etc.... 
2065-12-20         14*12      120*12
2061-10-31         18*12      800*12
2045-11-28         19*70      580*70
2043-10-31         21*11      12*11
2040-07-30         44*21      21*21
2049-06-30         1.2*64     17*64
2036-01-31         61.8*14    61*61

df1['col1'] 在几天前,我使用

对其进行了转换
df1['col1'] = (df1['col1'].values / np.timedelta64(1, 'D')).astype(int)

df1.dtypes = dtype('int32')

任何想法为什么它会抛出错误?

【问题讨论】:

    标签: python python-2.7 pandas dataframe timestamp


    【解决方案1】:

    例外是因为您乘以整个 DataFrame(包括时间戳列!),而不仅仅是单个列:

    df1['col1'].mul(df2)
    

    鉴于您可能想要的数据框:

    df1['col1'].mul(df2['col1'])
    

    如果您想一次处理多个列:

    df1['col1'].values[:, None] * df2[['col1', 'col2', ...]]  # explicitly list columns
    
    df1['col1'].values[:, None] * df2[df2.columns[1:]]        # all columns except the first
    

    【讨论】:

    • 谢谢!我有最后一个问题,当我尝试做除法时,我到处都有 Nan。有什么解释吗?我的 col1 中有一个 0,我尝试将整个 df2 除以它。 df2[df2.columns[1:]].div(df1['col1']) 应该有效吗?
    • NaN 在每一行还是在0 所在的行?
    • 无处不在。 .dtype 是 dtype('int32')
    • 这很奇怪。我无法重现那个。您能否为此提出一个新问题,包括一个最小的示例案例?在 cmets 中很难讨论这种问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    相关资源
    最近更新 更多