Reputation: 49
I need to change values of a column in 2 groups like country column has several value but I need US and Non -US in Pandas Dataframe. Please suggest how to achieve this in python dataframe.
I tried below code but no luck
1.
if df['Country'] != 'United-States':
df['Country'] = 'Non-US'
2.
df.loc[df['Country'] != 'United-States', 'Country'] = 'Non-US'
Upvotes: 2
Views: 310
Reputation: 40878
In addition to the NumPy version in @jezrael's answer, pandas also has its own Series.where()
function:
>>> df = pd.DataFrame({'Country': ['United-States', 'Canada', 'Slovakia']})
>>> df.Country.where(df.Country == 'United-States', 'Non-US')
0 United-States
1 Non-US
2 Non-US
The where method is an application of the if-then idiom. For each element in the calling DataFrame, if cond is True the element is used; otherwise the corresponding element from the DataFrame other is used.
The signature for DataFrame.where() differs from numpy.where(). Roughly df1.where(m, df2) is equivalent to np.where(m, df1, df2).
Upvotes: 0
Reputation: 862431
You need:
df = pd.DataFrame({'Country': ['United-States', 'Canada', 'Slovakia']})
print(df)
Country
0 United-States
1 Canada
2 Slovakia
df['Country'] = np.where(df['Country'] == 'United-States', 'US', 'Non-US')
Or:
df['Country'] = np.where(df['Country'] != 'United-States', 'Non-US', 'US')
Another solution:
df['Country'] = df['Country'].map({'United-States':'US'}).fillna('Non-US')
print (df)
Country
0 US
1 Non-US
2 Non-US
Upvotes: 5
Reputation: 13401
You can use apply function as below:
df['country']=df['country'].apply(lambda x: "Non-US" if x != 'United-States' else "United-States")
Upvotes: 0
Reputation: 600
Try the following:
US = df[df['Country']=='United-States']
Other = df[df['Country']!='United-States']
This will surely help
Upvotes: 1