【问题标题】:How to label unique values?如何标记唯一值?
【发布时间】:2019-10-07 22:30:36
【问题描述】:

我的数据集包含 48000 行作为输入文本和答案。答案有 89 个唯一值。我如何从文本答案标签中做出答案,例如 1 个唯一值等于 answer1,第二个等于 answer2,依此类推,直到答案 89。


> x               y                y_val
> hello     please push button 1   answer1
> what's up please push button 1   answer1
> be cool   please push button 1   answer1
>smth       please push button 1   answer1
>write num  please push button 1   answer1 
>hello      please push button 1   answer1
>what's up  please push button 1   answer1
>be cool        sure               answer2
>smth       sure                   answer2
>write num  sure                   answer2
>hello      sure                   answer2
> what's up perfect                answer3
> be cool   perfect                answer3
>smth       call me                answer89
>write num  call me                answer89

================================================ ==========================

我想更改“请按按钮 1”将变为 answer1,“确定”变为 answer2。我有 89 个唯一值,因此我需要将它们全部更改为 y_values 变为仅包含 answer1-answer89 的列。

【问题讨论】:

  • 请展示您的数据框示例
  • x y 你好,请按一下按钮 1 怎么了确定 smth 确定 写 num 确定 hello 确定 怎么了 完美 很酷 完美 smth call me write num call me

标签: python pandas dataframe label pandas-groupby


【解决方案1】:

我有点困惑,您是否只想在数据框中附加一个重新编码的列,将您的“y”列值标记为 answer1-answer89?

如果是,此代码将为您执行此操作:

seen = set()
y_val = []
x = list(range(1,50))

for i in range(len(data)):
    if any((str(data.iloc[i,1]) == y) for y in seen):
        y_val.append(y_val[-1])
    else:
        y_val.append('answer'+str(x[0]))
        seen.add(str(data.iloc[i,1]))
        x.pop(0)

data['y_values'] = y_val
print(data)

这种方式假设数据按字母顺序按“y”列排序,并且您可以按照该排序进行重新编码。只需将“数据”替换为您的熊猫数据集的名称,并确保 iloc 对您的列是正确的。我确信有一种更有效或 Pythonic 的方法可以做到这一点,但这是我想出来的。

希望这有帮助!

【讨论】:

  • 我需要将 y 的值更改为表单答案和该答案的唯一编号 > x y y_val > 你好,请按下按钮 1 answer1 > 怎么了,请按下按钮 1 answer1 >smth call me answer89 >写 num 打电话给我 answer89
  • 哦,所以 x 和 y 的每一对都相当于一个唯一的 answer1-89?
  • new=[] for answers in dataset.y: for i in range(0,len(dataset.y.unique())): if answers==dataset.y.unique()[ i]: new.append("answer"+str(i))
猜你喜欢
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2015-10-22
相关资源
最近更新 更多