如何根据pandas Dataframe中的索引范围从列表中删除元素。
假设DataFrame类似于
df:
values size
0 [1,2,3,4,5,6,7] 2 #delete first 2 elements from list
1 [1,2,3,4] 3 #delete first 3 elements from list
2 [9,8,7,6,5,4,3] 5 #delete first 5 elements from list
预期输出为
df:
values size
0 [3,4,5,6,7] 2
1 [4] 3
2 [4,3] 5
答案 0 :(得分:2)
结合索引使用列表理解:
df['values'] = [i[j:] for i, j in zip(df['values'], df['size'])]
print (df)
values size
0 [3, 4, 5, 6, 7] 2
1 [4] 3
2 [4, 3] 5
答案 1 :(得分:2)
使用df.apply
import pandas as pd
df = pd.DataFrame({"values": [[1,2,3,4,5,6,7], [1,2,3,4], [9,8,7,6,5,4,3]], "size": [2, 3, 5]})
df["values"] = df.apply(lambda x: x["values"][x['size']:], axis=1)
print(df)
输出:
size values
0 2 [3, 4, 5, 6, 7]
1 3 [4]
2 5 [4, 3]
答案 2 :(得分:0)
可以在基本的Python中使用map
dat['values'] = pd.Series(map(lambda x, y : x[y:], dat['values'], dat['size']))
返回
dat
Out[34]:
values size
0 [3, 4, 5, 6, 7] 2
1 [4] 3
2 [4, 3] 5