我想創建一個獲取多個熊貓列的函式,并進行額外的字串操作以創建另一列。字串操作必須依賴于發送到函式的其他一些字串常量。
import pandas as pd
items_df = pd.DataFrame({
'id': [302, 504, 708, 103, 343, 565],
'name': ['Watch', 'Camera', 'Phone', 'Shoes', 'Laptop', 'Bed'],
'surname': ['McArthur', 'Martinez', 'Whatever', 'Oslo', 'Berlin', 'Furniture'],
'price': [300, 400, 350, 100, 1000, 400],
'discount': [10, 15, 5, 0, 2, 7]
})
# column depending on two columns (strings) and other with f strings
def create_new(idd,name,header,footer):
# this does not work
try:
result = header 'web' idd name.str footer
except:
print('result does not work')
try:
result = f'''{header}.web{idd}{name}{footer}'''
except:
print('result2 does not work')
print(type(result))
result = result "?serveAsMime=application/pdf;"
return result
header = 'https//:'
footer = '.com'
items_df['link'] = create_new(items_df['id'].apply(str),items_df['name'],header,footer)
在函式中,結果 1 不起作用(錯誤),結果 2 起作用,但沒有按需要計算結果,而是將整個系列添加到每個元素中。
所以基本上問題是我如何將兩個系列和兩個字串傳遞給一個函式并用它們進行字串操作。items_df['link'] 的預期輸出是像 'https//:web302Watch.com' 這樣的字串(對于第一行)
我實際得到的是: https//:.web0 302\n1 504\n2 708\n3 ...(對于第一行)
uj5u.com熱心網友回復:
國際大學聯盟:
items_df['url'] = 'https://web' items_df['id'].astype(str) items_df['name'] '.com'
print(items_df)
輸出:
id name surname price discount url
0 302 Watch McArthur 300 10 https://web302Watch.com
1 504 Camera Martinez 400 15 https://web504Camera.com
2 708 Phone Whatever 350 5 https://web708Phone.com
3 103 Shoes Oslo 100 0 https://web103Shoes.com
4 343 Laptop Berlin 1000 2 https://web343Laptop.com
5 565 Bed Furniture 400 7 https://web565Bed.com
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/424884.html
