我有一個資料集,我正在嘗試拆分列位置的值。我擁有的資料集是:- 我擁有的資料集
資料集有 56 個空值,因此我使用以下代碼獲取這些空值的索引:-
nan = []
for i in range(len(data['location'])):
if type(data['location'][i]) == float:
nan.append(i)
完成后,我運行了另一個回圈:-
for i in range(len(data['location'])):
if i in nan:
data['city'] = np.nan
else:
data['city'] = data['location'][i].split(',')[1]
這給了我一個錯誤說,
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_15176/2022247788.py in <module>
3 data['city'] = np.nan
4 else:
----> 5 data['city'] = data['location'][i].split(',')[1]
IndexError: list index out of range
雖然它給了我價值,但它沒有給出正確的價值。從位置中可以看出,第一個值是 NaN,所以我想要城市中的 NaN,列中的第二個值是 Canandaigua, NY,所以我希望在城市中有 NY。
我還嘗試使用以下代碼直接拆分它們:-
data[['town','city2']] = data['location'].str.split(',',expand=True)
但得到一個錯誤: -
ValueError: Columns must be the same length as key
uj5u.com熱心網友回復:
你可以做這樣的事情來讓城市進入另一列
data['city'] = data.location.str.split(",").str[1]
這將回傳城市,如果不可用,則回傳 NaN
編輯:然后試試這個。
data['city'] = data[~data.location.isna()].location.str.split(",").apply(lambda x: x[0] if len(x) == 1 else x[1])
這將檢查拆分字串的長度是否僅為 1,然后按原樣回傳字串。否則,回傳第二個值。
uj5u.com熱心網友回復:
這也應該作業
### Comma Condition
comma_condtn = (df['location'].str.contains(',')) & (df['location'].notna())
### Extract city
df.loc[comma_condtn, 'city_2'] = df['location'].apply(lambda x : str(x).split(',').pop())
### Condition without commas
df.loc[df['city_2'].isna(), 'city_2'] = df['location']
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/486562.html
