I know I'm missing something minor so coming here for help rather than keep spinning my wheels -
I've found the index of the character I would like from a string here:
df['letter_idx']= df['string'].str.find(':')-1
How can I then find the character at this location? (I know below isn't correct, but something like this)
df['letter'] = df['string']['letter_idx']
Is there a simpler way to do this?
You can use the apply
method with both "string", "letter_idx" columns.
df["letter"] = df[["string", "letter_idx"]].apply(lambda row: row.string[row.letter_idx], axis=1)
OR you can use the zip
function.
>>> df = pandas.DataFrame({"string": ["MyString:123", "Another One: 321"]})
>>> df['letter_idx']= df['string'].str.find(':')-1
>>> df["letter"] = [s[i] for s, i in zip(df.string, df.letter_idx)]
>>> df
string letter_idx letter
0 MyString:123 7 g
1 Another One: 321 10 e
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.