【问题标题】:Find automatically the index of a list item which is contained in a specific pandas column for each row自动查找列表项的索引,该列表项包含在每一行的特定 pandas 列中
【发布时间】:2019-10-24 03:40:14
【问题描述】:

我试图自动查找而不使用列表项的索引,该列表项包含在每行的特定熊猫列中。

想象一下,我有一个包含 names = ["U9", "Z9", "H10"] 的列表和一个带有包含以下内容的列的 pandas 数据框

dat['col1'] = ["U9", "U9", "U9", "Z9", "Z9", "H10", "H10", "H10", "H10", "H10"] 

我正在尝试将第一个代码替换为从 mask 开始的第二个代码,但出现以下错误。


for i in range(len(dat)):
    index = names.index(dat['col1'][i])
    if index < len(names)-1:
        dat.loc[i, 'col2'] = names[index + 1]
    else:
        break

mask = []

for i in range(len(dat)):
    mask.append(names.index(dat['col1'][i]) < len(names) - 1)


dat['col2'] = np.where(mask, names[names.index(dat['col1'])+1], np.NaN)

我得到的错误是

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

这是因为names[names.index(dat['col1'])+1] 没有对dat['col1'] 中的每一行进行迭代。

所以我想要的是在不使用下面提到的 for 的情况下遍历 pandas 中的行,并将 dat['col1'] 的值分配给 dat['col2'],但进行了转移。预期的结果应该是这样的

dat['col2'] = ["Z9", "Z9", "Z9", "H10", "H10", nan, nan, nan, nan, nan]

【问题讨论】:

    标签: python pandas list indexing


    【解决方案1】:

    您可以在从列表创建字典后使用series.map()

    d={a:b for a,b in zip(names,names[1:])}
    #{'U9': 'Z9', 'Z9': 'H10'}
    dat['col2']=dat.col1.map(d)
    

    0     Z9
    1     Z9
    2     Z9
    3    H10
    4    H10
    5    NaN
    6    NaN
    7    NaN
    8    NaN
    9    NaN
    

    使用get,您还可以获得索引与值:

    pd.Series(d).get(dat.col1)
    

    col1
    U9      Z9
    U9      Z9
    U9      Z9
    Z9     H10
    Z9     H10
    H10    NaN
    H10    NaN
    H10    NaN
    H10    NaN
    H10    NaN
    

    【讨论】:

      猜你喜欢
      • 2014-10-13
      • 2018-07-07
      • 1970-01-01
      • 1970-01-01
      • 2023-02-11
      • 2014-05-12
      • 1970-01-01
      • 2013-08-14
      • 1970-01-01
      相关资源
      最近更新 更多