Reputation: 85
I'm using Python lib pandas. For all the rows in a data frame in which a specific column matches a specific string, I want to copy that value from the column at the left to the current column.
For example, for all rows with the column City with the value 'not available', I want to copy the value from the column at the left, let's say Country, to the current column City.
import pandas as pd
df = pd.DataFrame({'Country': ['France','England','U.S.A','Spain'],
'City': ['Paris','London','not available','not available']})
print(df)
Country City
0 France Paris
1 England London
2 U.S.A not available
3 Spain not available
Upvotes: 0
Views: 969
Reputation: 1393
There are a lot of ways to achieve this. One is using the loc property:
import pandas as pd
df = pd.DataFrame({'Country': ['France','England','U.S.A','Spain'],
'City': ['Paris','London','N/A','N/A']})
print(df)
Country City
0 France Paris
1 England London
2 U.S.A N/A
3 Spain N/A
Then:
df.loc[df['City'] == 'N/A', 'City'] = df['Country']
Country City
0 France Paris
1 England London
2 U.S.A U.S.A
3 Spain Spain
For more complex recipes check the Cookbook
Upvotes: 2