【问题标题】:Add a tuple to a specific cell of a pandas dataframe将元组添加到熊猫数据框的特定单元格
【发布时间】:2015-03-13 00:48:50
【问题描述】:

就在我认为自己掌握了 Python 和 Pandas 的窍门时,另一个看似简单的问题突然出现了。我想将元组添加到熊猫数据框的特定单元格。这些元组需要根据数据帧中其他单元格的内容即时计算 - 换句话说,我无法轻松地预先计算所有元组并将它们添加为单个数组。

例如,我定义了一个包含一些数据的数据框并添加了几个空列:

import pandas as pd
import bumpy as np
tempDF = pd.DataFrame({'miscdata': [1.2,3.2,4.1,2.3,3.3,2.5,4.3,2.5,2.2,4.2]})
tempDF['newValue'] = np.nan
tempDF['newTuple'] = np.nan

我可以滚动浏览“newValue”列的每个单元格并添加一个整数值而不会出现问题:

anyOldValue = 3.5
for i in range(10):
    tempDF.ix[(i,'newValue')] = anyOldValue

print tempDF

但是,如果我尝试添加一个元组,我会收到一条错误消息:

anyOldTuple = (2.3,4.5)
for i in range(10):
    tempDF.ix[(i,'newTuple')] = anyOldTuple

print tempDF

我收到了几条错误消息,包括:

ValueError: Must have equal len keys and value when setting with an ndarray

……和……

ValueError: setting an array element with a sequence.

我确定我在单元格中看到了带有元组(或列表)的数据框 - 不是吗?任何有关如何使此代码正常工作的建议将不胜感激。

【问题讨论】:

    标签: python pandas tuples dataframe


    【解决方案1】:

    你可以使用set_value:

    tempDF.set_value(i,'newTuple', anyOldTuple)
    

    还要确保该列不是浮点列,例如:

    tempDF['newTuple'] = 's' # or set the dtype
    

    否则会报错。

    【讨论】:

    【解决方案2】:

    set_value 已弃用。

    您可以只使用 .at[] 或 iat[]

    例如some_df.at[ idx, col_name] = any_tuple

    【讨论】:

    • 谢谢!我的问题的完美答案! :)
    【解决方案3】:

    正如J.Melody 指出的那样,.at[].iat[] 可用于将元组分配给单元格,如果列的dtype 为object

    简单示例:

    df initialized as:
       a  b  c
    0  0  1  2
    1  3  4  5
    2  6  7  8
    
    df containing tuple:
       a       b  c
    0  0  (1, 2)  2
    1  3       4  5
    2  6       7  8
    

    代码:

    import numpy as np
    import pandas as pd
    
    df = pd.DataFrame(np.arange(9).reshape((3,3)), columns=list('abc'), dtype=object)
    print('df initialized as:', df, sep='\n')
    df.at[0,'b'] = (1,2)
    print()
    print('df containing tuple:', df, sep='\n')
    

    注意:

    如果你跳过, dtype=object,你最终会得到

    ValueError: setting an array element with a sequence.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2022-01-12
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      相关资源
      最近更新 更多