简体   繁体   English

根据熊猫数据框中的另一个列表创建一个列表

[英]Create a list according to another list in panda dataframe

I have two dataframes as below:我有两个数据框如下:

df1 df1

Sites
['a']       
['b', 'c', 'a', 'd']        
['c']       

df2 df2

Site cells
a       2
b       4
c       3
d       5

what i need is to add a column in df1 with list of cells corresponding to list in df1 like我需要的是在 df1 中添加一列,其中包含与 df1 中的列表相对应的单元格列表,例如

result_df结果_df

Sites                   Cells
['a']                   [2]
['b', 'c', 'a', 'd']    [4,3,2,5]   
['c']                   [3]

I wrote below, just the column is map object,我在下面写了,只是列是地图对象,

df1['Cells'] = df1['Sites'].map(lambda x: map(df2.set_index('Site')['cells'],x))

I tried using list to convert it to list but I get this error我尝试使用列表将其转换为列表,但出现此错误

df1['Cells'] = df1['Sites'].map(lambda x: list(map(df2.set_index('Site')['cells'],x)))
TypeError: 'Series' object is not callable

Let us do让我们做

df1['value'] = df1.Sites.map(lambda x : df2.set_index('Site')['cells'].get(x).tolist())
df1
Out[728]: 
          Sites         value
0           [a]           [2]
1  [b, c, a, d]  [4, 3, 2, 5]
2           [c]           [3]

If you have some Sites in df1 not in df2 try with explode如果您在 df1 中有一些站点不在 df2 中,请尝试使用explode

df1['new'] = df1.Sites.explode().map(df2.set_index('Site')['cells']).groupby(level=0).agg(list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM