![](/img/trans.png)
[英]Can we use a Pandas function in a Spark DataFrame column ? If so, how?
[英]How can we use a pandas dataframe column in string formating
不知道怎么問。 想要使用formating.like在字符串中添加行值如果我有如下的df:
事物 | 數量 | 地方 |
---|---|---|
蘋果 | 1 | 桌子 |
芒果 | 4 | 椅子 |
可樂 | 3 | 地面 |
筆 | 2 | 桌子 |
我想要 output 如下所示:
事物 | 數量 | 地方 | 細繩 |
---|---|---|---|
蘋果 | 1 | 桌子 | 1 桌上的蘋果 |
芒果 | 4 | 椅子 | 4 椅子上的芒果 |
可樂 | 3 | 地面 | 3 地板上的可樂 |
筆 | 2 | 桌子 | 2 筆放在桌子上 |
我df['string'] = f'{df['qty']} {df['things']} on the {df['place']}'
但沒有得到確切的結果。
只需使用:-
df['string']=df['qty'].astype(str)+' '+df['things']+' on the '+df['place']
將 dataframe 轉換為字典。
以相同的格式將新數據列添加到字典中。
將字典轉換回 dataframe
data_dict = df.to_dict()
data_dict["string"] = ["1 Apple on the Table"......]
pd.Dataframe.from_dict(data_dict)
這是一篇可能有幫助的文章: https://re-thought.com/how-to-add-new-columns-in-a-dataframe-in-pandas/
您可以在此處使用pd.Series.str.cat
。
df["qty"].astype(str).str.cat(
[df["things"], ("on the " + df["place"])], sep=" "
)
0 1 Apple on the Table
1 4 Mango on the Chair
2 3 Coke on the Floor
3 2 Pen on the Table
Name: qty, dtype: object
如果你想使用f-string
,那么你可以在軸 1 上使用df.apply
(但這種方法很慢,應該作為最后的手段使用)。
df.apply(lambda x: f'{x.qty} {x.things} on the {x.place}', axis=1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.