Pandas - conditionally select source column of data for a new column based on row value
Using DataFrame.where
's other
argument and pandas.concat
:
>>> import pandas as pd
>>>
>>> foo = pd.DataFrame([
... ['USA',1,2],
... ['Canada',3,4],
... ['Canada',5,6]
... ], columns=('Country', 'x', 'y'))
>>>
>>> z = foo['x'].where(foo['Country'] == 'USA', foo['y'])
>>> pd.concat([foo['Country'], z], axis=1)
Country x
0 USA 1
1 Canada 4
2 Canada 6
If you want z
as column name, specify keys
:
>>> pd.concat([foo['Country'], z], keys=['Country', 'z'], axis=1)
Country z
0 USA 1
1 Canada 4
2 Canada 6
This would work:
In [84]:
def func(x):
if x['Country'] == 'USA':
return x['x']
if x['Country'] == 'Canada':
return x['y']
return NaN
foo['z'] = foo.apply(func(row), axis = 1)
foo
Out[84]:
Country x y z
0 USA 1 2 1
1 Canada 3 4 4
2 Canada 5 6 6
[3 rows x 4 columns]
You can use loc
:
In [137]:
foo.loc[foo['Country']=='Canada','z'] = foo['y']
foo.loc[foo['Country']=='USA','z'] = foo['x']
foo
Out[137]:
Country x y z
0 USA 1 2 1
1 Canada 3 4 4
2 Canada 5 6 6
[3 rows x 4 columns]
EDIT
Although unwieldy using loc
will scale better with larger dataframes as the apply here is called for every row whilst using boolean indexing will be vectorised.
Here is a generic solution to selecting arbitrary columns given a value in another column.
This has the additional benefit of separating the lookup logic in a simple dict
structure which makes it easy to modify.
import pandas as pd
df = pd.DataFrame(
[['UK', 'burgers', 4, 5, 6],
['USA', 4, 7, 9, 'make'],
['Canada', 6, 4, 6, 'you'],
['France', 3, 6, 'fat', 8]],
columns = ('Country', 'a', 'b', 'c', 'd')
)
I extend to an operation where a conditional result is stored in an external lookup structure (dict
)
lookup = {'Canada': 'd', 'France': 'c', 'UK': 'a', 'USA': 'd'}
Loop the pd.DataFrame
for each column stored in the dict
and use the values in the condition table to determine which column to select
for k,v in lookup.iteritems():
filt = df['Country'] == k
df.loc[filt, 'result'] = df.loc[filt, v] # modifies in place
To give the life lesson
In [69]: df
Out[69]:
Country a b c d result
0 UK burgers 4 5 6 burgers
1 USA 4 7 9 make make
2 Canada 6 4 6 you you
3 France 3 6 fat 8 fat