我有一個包含多列的資料框,其中兩列具有相同的名稱(“手機”),有些值為空,有些則不是,但總會有兩列之一填充電話號碼:
mobilephone mobilephone
0 999000111 999000111
1 999000222
2 999000333
3 999000444 999000444
我將如何只保留這些列中的一個,但用第二列中的值填充第一列中的空值?
uj5u.com熱心網友回復:
首先,找到第二個重復列的索引。然后更改此列的名稱并用于.loc[]填補空白:
col_name = 'mobilephone'
index_second_column = np.where(df.columns.duplicated())[0][0]
df.columns.values[index_second_column] = '_1'
df.loc[df[col_name].isnull(), colname] = df[col_name '_1']
df.drop(columns = col_name '_1', inplace=True)
uj5u.com熱心網友回復:
使用以下代碼可以輕松解決您的問題:
# renaming the columns
df.columns = ['mobilephone1', 'mobilephone2']
# filling blank cell with second column data
df['mobilephone1']=df['mobilephone1'].fillna(df['mobilephone2'])
# if you want you canrenam the columns again
df.columns = ['mobilephone', 'mobilephone']
讓我知道這是否對您有幫助??
uj5u.com熱心網友回復:
首先,您需要找到這兩列的位置。如果空單元格不是 nan:
df = df.replace(r'^\s*$', np.nan, regex=True)
然后使用fillna()并在字典中定義引數。
df = df.fillna({df.columns[phone_call_position]:df.columns[other_column_phone_call_position]}).rename(columns={df.columns[phone_call_position]:'mobilephone_main'}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/525776.html
標籤:Python熊猫数据框
