【问题标题】:columns names are not matching with row values as expected列名与预期的行值不匹配
【发布时间】:2022-01-01 19:12:45
【问题描述】:
data = pd.DataFrame({'id':[1,  2 , 3],

                   'question': ['first country visited?', 'first city visited?' , 'two cities we love?'],
                   'answer1': ['UK', 'Paris', 'CA'],
                   'answer2': ['US', 0.4, 'Paris'],
                   'answer3': ['CA', 'London', 'London'],
                   'correct': [['UK'], [0.4], ['London, Paris, 0.4']]
                   })

数据:

    id  question                 answer1    answer2   answer3   correct
0   1   first country visited?      UK       US        CA       [UK]
1   2   first city visited?         Paris   0.4       London    [0.4]
2   3   two cities we love?         CA     Paris      London    [London, Paris, 0.4]

我正在创建一个新列来检查是否在 answer1 或 answer2 或 answer3 列中找到正确列中的值。

cols = data.filter(like='answer').columns
data['correct_column'] = data[cols].apply(lambda s: ','.join((m:=s.isin(data.loc[s.name, 'correct']))[m].index), axis=1)

输出:

id  question                   answer1    answer2   answer3       correct                  correct_column
0   1   first country visited?        UK        US        CA        [UK]                     answer1
1   2   first city visited?           Paris     0.4       London    [0.4                     answer2
2   3   two cities we love?           CA        Paris     London    [London, Paris, 0.4]    

我在第三行得到一个空值。我已经尝试了几个小时,但我的原始数据没有成功!有没有更好的方法来实现这一目标?考虑我原始 df 中的不同数据类型,例如 floats、int & Str ..

【问题讨论】:

标签: python python-3.x pandas dataframe numpy


【解决方案1】:

这是一个更长的版本:

cols = data.filter(like='answer').columns

def app(s):
    (m:=[s[col] in (data.loc[s.name, 'correct']) for col in cols])
    return ', '.join(cols[m])

data['correct_column'] = data[cols].apply(app, axis=1)
data['correct_column']

和更短的版本可以完成同样的事情:

data['correct_column'] = data[cols].apply(lambda s: ', '.join(cols[(m:=[s[col] in (data.loc[s.name, 'correct']) for col in cols])]) , axis=1)
data['correct_column']

这将产生:

0             answer1
1             answer2
2    answer2, answer3
Name: correct_column, dtype: object

【讨论】:

  • 谢谢 Yusuf,代码再次在示例中完美运行,但我的原始数据出现错误(巨大的 df)TypeError: argument of type 'numpy.float64' is not iterable 有没有办法可以处理所有 df 的数据类型那么代码就可以工作了吗?
  • 当然。你能把出错的那一行贴出来吗?
  • ----> 4 (m:=[s[col] in (df.loc[s.name, 'correct']) for col in cols])
  • 我明白了。我认为问题可能在于correct 列中的某些值实际上可能不是列表,而是浮动,这导致了问题。尝试按如下方式对该列进行类型检查。如果值不是列表,只需将值包装在 list() 中。
  • 列表中的单个值应该仍然可以正常工作,如上面的 0.4 示例所示。您不应该在已经是列表的值上使用 list()。您是否尝试过调试器来查看数据框中的哪一行准确地引发了错误?
猜你喜欢
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-05
  • 2016-07-13
  • 1970-01-01
  • 2020-10-26
相关资源
最近更新 更多