In a dataframe with columns x and y , how would I write code so that if a row has an x string but a 'Not assigned' y string (the y column contains the string "Not assigned"), then the y string will be the same as the x string?
(Overwriting the "Not assigned" string in column y with the contents of column x )
You can use df.iterrows()
checking the values of the columns conditionally as you iterate.
import pandas as pd
df = pd.DataFrame(data={'x': [1,2,3], 'y': [6, "Not Assigned", 8]})
for index, value in df.iterrows():
if value['y'] == 'Not Assigned':
df['y'][index] = df['x'][index]
Output:
x y
0 1 6
1 2 2
2 3 8
df.loc[df['y']=='Not assigned', 'y'] = df.loc[df['y']=='Not assigned', 'x']
would do it
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.