我想知道如何用 location2 列中的字串值替換 location1 列中 'Singapore' 的字串值。在這種情況下,它們是Tokyo, Boston, Toronto和Hong Kong, Boston。
import pandas as pd
data = {'location1':["London, Paris", "Singapore", "London, New York", "Singapore", "Boston"],
'location2':["London, Paris", "Tokyo, Boston, Toronto", "London, New York", "Hong Kong, Boston", "Boston"]}
df = pd.DataFrame(data)
location1 location2
0 London, Paris London, Paris
1 Singapore Tokyo, Boston, Toronto
2 London, New York London, New York
3 Singapore Hong Kong, Boston
4 Boston Boston
uj5u.com熱心網友回復:
簡單地說,使用.loc和索引:
df.loc[df['location1'].eq('Singapore'), 'location1'] = df['location2']
print(df)
# Output:
location1 location2
0 London, Paris London, Paris
1 Tokyo, Boston, Toronto Tokyo, Boston, Toronto
2 London, New York London, New York
3 Hong Kong, Boston Hong Kong, Boston
4 Boston Boston
uj5u.com熱心網友回復:
我們可以使用以下numpy.where方法來做到這一點:
>>> import numpy as np
>>> df["location1"] = np.where(df["location1"] == 'Singapore', df["location2"], df["location1"])
>>> df
location1 location2
0 London, Paris London, Paris
1 Tokyo, Boston, Toronto Tokyo, Boston, Toronto
2 London, New York London, New York
3 Hong Kong, Boston Hong Kong, Boston
4 Boston Boston
uj5u.com熱心網友回復:
嘗試:
df['location1'] = df['location1'].mask(df['location1'] == 'Singapore')\
.fillna(df['location2'])
輸出:
location1 location2
0 London, Paris London, Paris
1 Tokyo, Boston, Toronto Tokyo, Boston, Toronto
2 London, New York London, New York
3 Hong Kong, Boston Hong Kong, Boston
4 Boston Boston
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/370798.html
上一篇:函式引數遍歷csv檔案值
下一篇:如何僅將字典值中的第一個字母大寫
