![](/img/trans.png)
[英]How do you extract specific values from a column in one dataframe and append them to a column in another dataframe? - Pandas
[英]How do groups of IDs in rows of one pandas dataframe and use them to extract records from another dataframe
我有两个数据框。 一个包含个人和家庭的联系信息。 另一个包含一个家庭的 ID 字段,后跟该家庭中的个人。 我想 select 来自第一个 dataframe 的所有记录,并插入一个与其关联的家庭 ID 的列。
最小可重复性:
df1 = pd.DataFrame({'Constituent Id':['111111','222222','333333','444444','555555','666666','777777'],
'Type':['Individual','Household','Individual','Household',
'Individual','Individual','Individual'],
'Name':['Panda Smith','Panda and Python','Python Jones','Postgres Family',
'Paul Postgres','Mary Postgres','Sqlite Postgres']})
df2 = pd.DataFrame({'Account_ID':['ABCDEF','GHIJKL'],
'Household_0':['222222','444444'],
'Individual_0':['111111','555555'],
'Individual_1':['333333','666666'],
'Individual_2':['','777777']})
导致:
>>> df1
Constituent Id Type Name
0 111111 Individual Panda Smith
1 222222 Household Panda and Python
2 333333 Individual Python Jones
3 444444 Household Postgres Family
4 555555 Individual Paul Postgres
5 666666 Individual Mary Postgres
6 777777 Individual Sqlite Postgres
>>> df2
Account_ID Household_0 Individual_0 Individual_1 Individual_2
0 ABCDEF 222222 111111 333333
1 GHIJKL 444444 555555 666666 777777
我想要做的是 append 到df1
的一列,其Account_ID
适用于帐户中的每个人。 家庭不是必需的,但如果我包括这些就可以了。
因为每个家庭的人数各不相同,所以如果不遍历每一行,我想不出一个很好的方法来做到这一点。 这似乎很不熊猫,我相信有更好的方法,也许是通过堆叠或其他方式。
在我的示例中,output 看起来像:
Constituent Id Type Name Account_ID
0 111111 Individual Panda Smith ABCDEF
1 222222 Household Panda and Python ABCDEF
2 333333 Individual Python Jones ABCDEF
3 444444 Household Postgres Family GHIJKL
4 555555 Individual Paul Postgres GHIJKL
5 666666 Individual Mary Postgres GHIJKL
6 777777 Individual Sqlite Postgres GHIJKL
IIUC需要melt
然后merge
如果。 Type
不是必需的,您可以从第二行和合并子句中省略它。
s = pd.melt(df2,id_vars='Account_ID',var_name='Type',value_name='Constituent Id')
s['Type'] = s['Type'].str.split('_',expand=True)[0]
print(s.head(5))
Account_ID Type Constituent Id
0 ABCDEF Household 222222
1 GHIJKL Household 444444
2 ABCDEF Individual 111111
3 GHIJKL Individual 555555
4 ABCDEF Individual 333333
df3 = pd.merge(df1,
s,
on=['Type','Constituent Id'],
how='left'
)
print(df3)
Constituent Id Type Name Account_ID
0 111111 Individual Panda Smith ABCDEF
1 222222 Household Panda and Python ABCDEF
2 333333 Individual Python Jones ABCDEF
3 444444 Household Postgres Family GHIJKL
4 555555 Individual Paul Postgres GHIJKL
5 666666 Individual Mary Postgres GHIJKL
6 777777 Individual Sqlite Postgres GHIJKL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.