Reputation: 87
I have the following DataFrame (reformatted a bit):
f_name l_name n f_bought l_bought
0 Abraham Livingston 24 1164 1187
1 John Brown 4 1188 1191
2 Samuel Barret 16 1192 1207
3 Nathan Blodget 4 1208 1212
4 Bobby Abraham 1 1212 1212
I want to create a column, bought
, that is a list range(df[f_bought], df[l_bought])
.
I've tried:
def getRange(l1,l2):
r = list(range(l1, l2))
df.apply(lambda index: getRange(df['f_bond'], df['l_bond']),axis=1)
but it results in a TypeError:
"cannot convert the series to <type 'int'>", u'occurred at index 0'
I've tried a df.info(), and both columns are type int64.
I'm wondering if I should use something like df.loc[]
or similar? Or something else entirely?
Upvotes: 2
Views: 2454
Reputation: 78883
You should be able to do this using apply
which is for applying a function to every row or every column of a data frame.
def bought_range(row):
return range(row.f_bought, row.l_bought)
df['bought_range'] = df.apply(bought_range, axis=1)
Which results in:
f_name l_name n f_bought l_bought \
0 Abraham Livingston 24 1164 1187
1 John Brown 4 1188 1191
2 Samuel Barret 16 1192 1207
3 Nathan Blodget 4 1208 1212
4 Bobby Abraham 1 1212 1212
bought_range
0 [1164, 1165, 1166, 1167, 1168, 1169, 1170, 117...
1 [1188, 1189, 1190]
2 [1192, 1193, 1194, 1195, 1196, 1197, 1198, 119...
3 [1208, 1209, 1210, 1211]
4 []
One word of warning is that Python's range
doesn't include the upper limit:
In [1]: range(3, 6)
Out[1]: [3, 4, 5]
It's not hard to deal with (return range(row.f_bought, row.l_bought + 1)
) but does need taking into account.
Upvotes: 2