如何根据特定条件用列表值替换 Pandas Dataframes 中的元素?

如何解决如何根据特定条件用列表值替换 Pandas Dataframes 中的元素?

我有一个 CSV 文件,其中包含 2 列,查询和描述。这是文件的示例描述:-

| Query                                        | Description |
| --------                                     | -------------- |
| What is the type of \<mach-name> machine>    |  \<mach-name> is ...       |
| What is the use of \<mach-name> machine>     |  The use of \<mach-name> is ...         |
| How long it takes to rain in \<state-name>   | It rains for ... hours in \<state-name>          |
| What is the best restaurant in \<state-name> | \<state-name>'s best food is in ...         |
|
...
etc.

每个查询列和描述列都有这样的唯一字符串。假设通过 Pandas 将 CSV 文件读入数据帧 df。目标是根据特定条件替换\<>类型的元素,例如\<mach-name>等。

需要通过将标签 替换为相应的列表元素来进行这些替换。

mach_name = ["Drilling","ABC",XYZ".... etc.]
state_name = ["New York","London","Delhi"... etc.]

示例:if(\<mach-name>) 出现在任何行的查询和说明列中,替换 mach_name 列表中相应元素的标签。所以,例如如果 mach_name 列表有 10 个元素,则需要将更多这样的句子附加到数据框 df。 预期的输出是这样的:

| Query                                   | Description |
| --------                                | -------------- |
| What is the type of Drilling machine.   |  Drilling is ...        |
| What is the type of ABC machine.        |  ABC is ...        |
| What is the type of XYZ machine.        |  XYZ is ...      |
| What is the use of Drilling machine     |  The use of Drilling is ...        |
| What is the use of ABC machine          |  The use of ABC is ...       |
| What is the use of XYZ machine.         |  The use of XYZ is ...       |
| How long it takes to rain in New York   | It rains for ... hours in New York          |
| How long it takes to rain in London     | It rains for ... hours in London          |
| How long it takes to rain in Delhi      | It rains for ... hours in Delhi          |

| What is the best restaurant in New York | New York's best food is in ...         |
| What is the best restaurant in London   | London's best food is in ...         |
| What is the best restaurant in Delhi    |Delhi's best food is in ...         |
|

....等

例如,我希望使用 str.replace() 执行简单的 Python 替换,但它可能会涉及用于迭代 Pandas 数据帧的 for 循环,因此答案建议不要迭代数据帧,而是我找不到一种明确的方法来根据这些条件替换值,同时还根据列表元素附加新行。任何帮助/指导表示赞赏。谢谢。

解决方法

如果您读取原始 csv,处理它,然后将结果转换为 Pandas 数据帧,这会更容易,但如果您之前需要读取数据帧,这可能是一个选项:

data=[ {"query": "What is the type of \<mach-name> machine>","description": "\<mach-name> is ..."},{"query": "What is the use of \<mach-name> machine>","description": "The use of \<mach-name> is ..."},{"query": "How long it takes to rain in \<state-name>","description": "It rains for ... hours in \<state-name>"}]
      
df = pd.DataFrame(data)

#mark rows that should that satisfy the conditions
df["replace_mach"] = df['query'].str.contains('\<mach-name>') &\ 
                     df['description'].str.contains('\<mach-name>')
df["replace_state"] = df['query'].str.contains('\<state-name>') &\ 
                      df['description'].str.contains('\<state-name>')


dfs_list = []
mach_name = ["Drilling","ABC","XYZ"]
state_name = ["New York","London","Delhi"]


for n in mach_name:
    aux = df[df["replace_mach"]].copy()
    aux["query"] = aux["query"].str.replace(r"\\<mach-name>",n)
    aux["description"] = aux["description"].str.replace(r"\\<mach-name>",n)
    dfs_list.append(aux)
    
for n in state_name:
    aux = df[df["replace_state"]].copy()
    aux["query"] = aux["query"].str.replace(r"\\<state-name>",n)
    aux["description"] = aux["description"].str.replace(r"\\<state-name>",n)
    dfs_list.append(aux)
    
# add records without wild cards to dataframe
dfs_list.append(df[~((df["replace_mach"])|(df["replace_state"]))]

replaced_df = pd.concat(dfs_list)
replaced_df

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?