![](/img/trans.png)
[英]Selecting rows from DF1 where column values match values from a column from DF2
[英]Set new column values in pandas DataFrame1 where DF2 column values match DF1 index
我想在pandas數據框中設置一個新列,並使用dataframe2上的groupby計算值。
DF1:
col1 col2
id
1 'a'
2 'b'
3 'c'
DF2:
id col2
index
1 1 11
1 1 22
1 1 12
1 1 45
3 3 83
3 3 11
3 3 35
3 3 54
我想按“ id”對DF2進行分組,然后對“ col2”應用一個函數以將結果放入DF1中的相應索引。 如果沒有該特定索引的組,那么我想用NaN填充...
ret_val = DF2.groupby('id').apply(lambda x: my_func(x['col_2']))
col1 col2
id
1 'a' ret_val
2 'b' NaN
3 'c' ret_val
...雖然我不太清楚如何實現這一目標
在df1.index
系列上使用map
。
In [5327]: df1['col2'] = df1.index.to_series().map(df2.groupby('id')
.apply(lambda x: my_func(x['col2'])))
In [5328]: df1
Out[5328]:
col1 col2
id
1 a 360.0
2 b NaN
3 c 536.0
細節
In [5322]: def my_func(x):
...: return x.sum()
...:
In [5323]: df2.groupby('id').apply(lambda x: my_func(x['col2']))
Out[5323]:
id
1 360.0
3 536.0
dtype: float64
In [5324]: df1.index.to_series().map(df2.groupby('id').apply(lambda x: my_func(x['col2'])))
Out[5324]:
id
1 360.0
2 NaN
3 536.0
Name: id, dtype: float64
首先在df2的col2上應用該函數,然后使用pd.concat
將col2
放入df中,因為它為空。
x = df2.groupby('id')['col2'].apply(sum) # instead of sum use your own function
ndf = pd.concat([df.drop('col2',1),x],1)
col1 col2 id 1 'a' 90.0 2 'b' NaN 3 'c' 183.0
@Zero提出的簡單直截了當的建議
df1['col2'] = df2.groupby('id')['col2'].apply(sum)
您可以用.apply(lambda x : your_func(x))
代替sum
df1.col2=df.set_index('id').groupby(level='id').sum()
df1
Out[975]:
col1 col2
id
1 'a' 90.0
2 'b' NaN
3 'c' 183.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.