Can we pass a column instead of a variable to access nth item of a list?

Viewed 46

My data contains multiple columns, on which I have done a group by and given row numbers based on the group by. I'm using python here The column 'Text' is a list of strings. The entire 'Text' was initially 1 string, which is split into a list with ; as the delimiter. Rownumber are integers. What I want to do here is, consider Rownum as a pointer towards output column. If Rownum= 0, then my output should be Text[0], i.e a.

If Rownum = 2, Output should be 2nd item of the list Text, Text1, i.e b

To achieve this, I tried:

df['Outpu'] = df.apply(lambda x:x['Text'].split(';'),axis = 1)[df['Row_num']]

But I got the error "cannot reindex from a duplicate axis". Not entirely sure what it means. I have attached an image of my data and output, but also have written down the format incase image isn't available. Hope I explained the situation clear enough. Original Text is not a,b,c: Just put it there for easier understanding. This is the text:

Text: [TAF KPHX 010246Z 0103/0206 VRB04KT P6SM FEW070 BKN160 ;FM010700 10005KT P6SM SCT060 BKN150 ;FM012100 21006KT P6SM SCT070 SCT140 ;FM020000 26005KT P6SM FEW070 SCT140]

Row num     Text          Output

0         [a,b,c,d]        a
1         [a,b,c,d]        b
2         [a,b,c,d]        c
3         [a,b,c,d]        d
0         [d,e,f]          d
1         [d,e,f]          e
2         [d,e,f]          f
1 Answers

As i see, Delimeter should be "," not ";". Since "Text" is a single string then first remove square brackets uisng replace() then split it by ',' and then extract the element using index in "Row_num"

df =pd.DataFrame({"Row_num": [0,1,2,3,0,1,2],"Text":['[a,b,c,d]', '[a,b,c,d]', '[a,b,c,d]', '[a,b,c,d]', '[d,e,f]', '[d,e,f]', '[d,e,f]']})
df["Output"] = df.apply(lambda x: x.Text.replace("[","").replace("]","").split(",")[x.Row_num], axis=1)
print(df)
    Row_num Text    Output
0   0   [a,b,c,d]   a
1   1   [a,b,c,d]   b
2   2   [a,b,c,d]   c
3   3   [a,b,c,d]   d
4   0   [d,e,f]     d
5   1   [d,e,f]     e
6   2   [d,e,f]     f

Lets say you have "," as a delimeter in Text column then try:

df =pd.DataFrame({"Row_num": [0,1,2,3,4],"Text":["a;b;c;d;e"]*5})
df["Output"] = df.apply(lambda x: x.Text.split(";")[x.Row_num], axis=1)
print(df)
 Row_num    Text    Output
0   0   a;b;c;d;e   a
1   1   a;b;c;d;e   b
2   2   a;b;c;d;e   c
3   3   a;b;c;d;e   d
4   4   a;b;c;d;e   e

Make sure data is available in Text at mentioned Row_num

Related