简体   繁体   English

检查字符串以在火花数据框中创建新列

[英]Inspect a string to create a new column in spark dataframe

I have a Spark dataframe column with trading pairs that I need to use to create a new column with the name of the coin populated in it.我有一个带有交易对的 Spark 数据框列,我需要使用它来创建一个新列,其中填充了硬币的名称。

The first column "bot" contains "Polkadot/USD", I need a new column called "coin" that contains only the substring "Polkadot" of the bot column.第一列“bot”包含“Polkadot/USD”,我需要一个名为“coin”的新列,它只包含bot列的子字符串“Polkadot”。 Same for all other rows.所有其他行相同。 Basically the new column needs to have the substring "/USD" removed.基本上新列需要删除子字符串“/USD”。

How would the code look like to accomplish this.代码如何实现这一点。 I'm a crypto trader not a coder, so the more coding detail in the answer the better.我是一名加密交易员而不是编码员,所以答案中的编码细节越多越好。 Thank you.谢谢你。

Note: The notebook is a Python Notebook注意:notebook 是 Python Notebook

在此处输入图片说明

You can use regexp_replace to substitute a substring with another substring您可以使用regexp_replace用另一个子字符串替换一个子字符串

df.withColumn('coin', F.regexp_replace(F.col('bot'), '/USD', ''))

Example例子

# sample dataframe
df3 = spark.createDataFrame([
    ('BamBridge/USD', ),
    ('CLV/USD', ),
    ('ETH/USD', ),
    ('Polkadot/USD', ),
], ['bot'])

df3 = df3.withColumn('coin', F.regexp_replace(F.col('bot'), '/USD', ''))

df3.show()

+-------------+---------+
|          bot|     coin|
+-------------+---------+
|BamBridge/USD|BamBridge|
|      CLV/USD|      CLV|
|      ETH/USD|      ETH|
| Polkadot/USD| Polkadot|
+-------------+---------+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据另一列的字符串搜索在Spark Dataframe中创建具有功能的新列 - Create new column with function in Spark Dataframe based on a string search of another column 如果列在另一个 Spark Dataframe 中,Pyspark 创建新列 - Pyspark create new column based if a column isin another Spark Dataframe 如何在火花 sql dataframe 中创建一个新列 map? - How to map a column to create a new column in spark sql dataframe? Python Spark - 如何创建一个新列,在数据帧上对现有列进行切片? - Python Spark - How to create a new column slicing an existing column on the dataframe? 如果 DataFrame 包含特定字符串,则创建新列 - Create new column if DataFrame contains specific string 比较两列以在Spark DataFrame中创建一个新列 - Compare two columns to create a new column in Spark DataFrame 如何创建新的字符串列以从Spark中的时间戳提取整数? - How to create new string column extracting integers from a timestamp in Spark? 计算字符串中的位数,然后在 Pandas 数据框中创建具有计数的新列 - Count number of digits in a string, then create new column with counts in Pandas dataframe 如果该列包含另一个数据框的列中的字符串,则在该数据框中创建一个新列 - Create a new column in a dataframe if the column contains a string from a column of another dataframe 通过将一列列表或字符串与另一个列表匹配来分组并创建新的数据框 - Group by matching a column of list or string with another list and create new dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM