【问题标题】:Understanding of .loc in Pandas to save variables in specific cell of a dataframe了解 Pandas 中的 .loc 以将变量保存在数据框的特定单元格中
【发布时间】:2021-10-27 05:23:38
【问题描述】:

当我想将变量保存在数据框的特定单元格中时,我不理解 .loc.at 的行为。有人可以帮我理解吗?

我失败的工作示例:

import pandas as pd
import numpy as np
print(pd.__version__)
from platform import python_version
print(python_version())



df=pd.DataFrame(index=[0,1,2,3],columns=['A','B'])

df = pd.DataFrame({'a':[np.array([1,2,3]), np.array([4,5,6]), np.array([7,8,9]), np.array([10,11,12]), np.array([13,14,15])],'b':[5,5,12,123,6]})

display(df)
df.loc[0,'c']='string 0'
df.loc[1,'c']='string 1'
df.loc[2,'c']='string 2'
df.loc[3,'c']='string 3'


print(df.index.values)

testdata=np.array(np.arange(0,3648,1),dtype=np.float32)
print('----------testdata----------')
print(type(testdata))
print(testdata.dtype)
print(testdata.shape)

print('----------file_handle----------')
file_handle=np.array([1],dtype=np.int64)
print(file_handle)
print(type(file_handle))
print(file_handle.dtype)


if not 'new_column' in df.columns:
        df=df.assign(new_column=None)


display(df)
df.loc[file_handle,'new_column']=[testdata]

display(df)

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

但是使用df.at[file_handle[0],'new_column']=[testdata]df.at[1,'new_column']=[testdata] 可以。我不明白。使用df.loc[file_handle[0],'new_column']=testdata 也不起作用。 在我的代码的其他地方,我可以使用行索引[1] 将字典或标量分配到一个特定位置,但不能使用 numpy 数组。

感谢您的解释和洞察。我会很感激了解,如何使用 .locat 以及它们接受哪些变量,既可以作为行索引,也可以作为存储在数据框中的项目。

【问题讨论】:

    标签: python arrays pandas dataframe numpy


    【解决方案1】:

    当右侧有一个 ndarray 时,Pandas 不会将其视为任何可以插入 DataFrame 的 Python 对象。相反,您会遇到一个代码路径,该路径试图在该数组的多个位置设置多个值,因此错误消息指出 when setting with an ndarray

    考虑一些有效的 multiloc 代码,例如

    df.loc[[0,1,3], ['b', 'new_column']] = np.array([[4,5], [6,7], [8,9]])
    

    这里左边的ilocs的形状和右边的数组的形状是一样的,并且所有的值都设置成功了。

    在您的代码中,Pandas 在此操作中将形状 (3648) 的 testdata 数组列表视为形状 (1, 3648) 的二维数组。此形状与左侧的 iloc 不匹配,因此 Pandas 会抛出无法匹配它们的错误。

    处理这个问题的正确方法是改用.at,它只能处理单个位置,不会碰到ndarray设置代码路径。

    【讨论】:

    • 嗨@w-m。谢谢你的解释。而且我猜,行索引是 int、np.ndarray 还是列表都没有关系?对于.loc,Pandas 会选择不同的代码路径来验证行索引?
    • 是的,您可以假设 Pandas 在.loc/.iloc 中的多位代码路径中以相同的方式处理所有类似列表的变体。
    猜你喜欢
    • 1970-01-01
    • 2019-07-19
    • 2018-03-05
    • 2020-11-12
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    相关资源
    最近更新 更多