move data from column2 to column1, if column1 is empty
In id 2 and 4 Phone1 is empty so transfer data from phone2 to phone1 df
id Phone1 Phone2
0 9073370404
1 9072765522 1234567890
2 9075611434
3 9073370404
4 9072765522
5 9075611434
id Phone1 Phone2
0 9073370404
1 9072765522 1234567890
2 9075611434
3 9073370404
4 9072765522
5 9075611434
CodePudding user response:
- Firstly, create the dataframe
import pandas as pd
import numpy as np
df = pd.DataFrame({
"Phone1":[9073370404, 9072765522, None, 9073370404, None, 9075611434],
"Phone2": [None, 1234567890, 9075611434, None, 9072765522, None]
})
print(df)
- Secondly, transfer data from phone2 to phone1
df["Phone1"] = df.apply(lambda row: row["Phone2"] if ((row["Phone1"] is None) or np.isnan(row["Phone1"])) else row["Phone1"], axis=1)
print(df)
Hope help you
CodePudding user response:
@Lowin Li
is not set the df["Phone2"], and import numpy
you can use apply
like @Lowin Li
import pandas as pd
dict = [
{"id":"0","Phone1":"9073370404",},
{"id":"1","Phone1":"9072765522","Phone2":"1234567890"},
{"id":"2","Phone2":"9075611434"},
{"id":"3","Phone1":"9073370404",},
{"id":"4","Phone2":"9072765522"},
{"id":"5","Phone1":"9075611434",}
]
df = pd.DataFrame.from_dict(dict)
def my_conbin(a, b):
if pd.isna(a):
return b
return a
def my_delete(a, b):
if a == b:
return None
return b
df['Phone1'] = df.apply(lambda row: my_conbin(row['Phone1'], row['Phone2']), axis=1)
df['Phone2'] = df.apply(lambda row: my_delete(row['Phone1'], row['Phone2']), axis=1)
print(df)
and df.iterrows()
is more simple:
import pandas as pd
dict = [
{"id":"0","Phone1":"9073370404",},
{"id":"1","Phone1":"9072765522","Phone2":"1234567890"},
{"id":"2","Phone2":"9075611434"},
{"id":"3","Phone1":"9073370404",},
{"id":"4","Phone2":"9072765522"},
{"id":"5","Phone1":"9075611434",}
]
df = pd.DataFrame.from_dict(dict)
for index,row in df.iterrows():
if pd.isna(row.Phone1):
df.loc[index, 'Phone1']= row.Phone2
df.loc[index, 'Phone2'] = None
print(df)
CodePudding user response:
def function1(s:pd.Series):
if pd.isna(s.Phone1):
s.Phone1,s.Phone2=s.Phone2,s.Phone1
return s
df1.apply(function1,axis=1)