如果pandas行中的值存在,则获取pandas行名称

如果pandas行中的值存在,则获取pandas行名称,pandas,dataframe,Pandas,Dataframe,我正在尝试将一个热键数据帧转换为二维帧 是否有任何方法可以迭代行和列,并用列名填充1的值 问题数据帧: +------------------+-----+-----+ | sentence | lor | sor | +------------------+-----+-----+ | sam lived here | 0 | 1 | +------------------+-----+-----+ | drack lived here | 1 | 0 |

我正在尝试将一个热键数据帧转换为二维帧

是否有任何方法可以迭代行和列,并用列名填充
1
的值

问题数据帧:

+------------------+-----+-----+
| sentence         | lor | sor |
+------------------+-----+-----+
| sam lived here   | 0   | 1   |
+------------------+-----+-----+
| drack lived here | 1   | 0   |
+------------------+-----+-----+

+------------------+------+
| sentence         | tags |
+------------------+------+
| sam lived here   | sor  |
+------------------+------+
| drack lived here | lor  |
+------------------+------+
解决方案数据帧:

+------------------+-----+-----+
| sentence         | lor | sor |
+------------------+-----+-----+
| sam lived here   | 0   | 1   |
+------------------+-----+-----+
| drack lived here | 1   | 0   |
+------------------+-----+-----+

+------------------+------+
| sentence         | tags |
+------------------+------+
| sam lived here   | sor  |
+------------------+------+
| drack lived here | lor  |
+------------------+------+

您可以分隔每列有1个的行。对于这些列,使用指定的名称替换值1,同时重命名列名

lor_df = df.loc[df["lor"].eq(1), "lor"].rename(columns={"lor": "tags"}).replace(1, "lor")
sor_df = df.loc[df["sor"].eq(1), "sor"].rename(columns={"sor": "tags"}).replace(1, "sor")
在此之后,使用连接各个结果,然后删除不需要的列

df["tags"] = pd.concat([lor_df, sor_df], sort=False)
df.drop(columns=["lor", "sor"], inplace=True)
为了确保我们可以使用的唯一值


如果同一个句子中有多个列,其中有1,该怎么办?你在努力解决哪一部分?如果多个列中有1,那么答案对你的用例有帮助吗?嘿,这很有帮助,我应该怎么做才能从第一个数据框中得到值,当出现重复值时?非常感谢,非常感谢您为此投入一点时间!