![](/img/trans.png)
[英]Pandas - ApplyMap using corresponding cell values from two different DataFrames
[英]How to join two dataframes and create a table counting corresponding values using Pandas?
我有表 1,它看起来像这样:
State District ID Race Party
0 GA 1 White Dem
1 SC 5 Black Dem
2 VA 4 Black Ind
3 VA 4 White Repub
4 NY 2 White Dem
5 GA 1 Black Dem
然后表 2 如下所示:
State District ID Event Type
0 GA 1 A; B; C
1 SC 5 B; A
2 VA 4 A; C
3 NY 2 B
4 GA 1 A; C
我希望生成的数据集看起来像这样:
State District ID # Event A # Event B # Event C # White # Black # Dem # Repub # Ind
0 GA 1 2 1 2 1 1 2 0 0
1 SC 5 1 1 0 1 1 0 0
2 VA 4 1 0 1 1 1 0 1 1
3 NY 2 0 1 0 1 0 1 0 0
在连接和创建计算相应行的结果表时,我非常不稳定,而且我也从未使用 Pandas 完成它,所以我不太确定如何开始。 哪个表甚至会被认为是左表或右表? 这可能是一个非常常见的用例,我只是无法理解代码行(或 SQL 查询,如果我使用的是 Postgres)会是什么样子。
首先我们加载样本数据。 注意我删除了列名中的空格以使其更容易
from io import StringIO
import pandas as pd
df1 = pd.read_csv(StringIO(
"""
State District_ID Race Party
0 GA 1 White Dem
1 SC 5 Black Dem
2 VA 4 Black Ind
3 VA 4 White Repub
4 NY 2 White Dem
5 GA 1 Black Dem
"""), delim_whitespace=True)
df2 = pd.read_csv(StringIO(
"""
State District_ID Event_Type
0 GA 1 A
1 SC 5 B
2 VA 4 A
3 NY 2 B
4 GA 1 A
"""), delim_whitespace=True)
然后我们创建三个 pivot 表,分别用于 Race、Party、Event_Type:
dfa = df1.assign(count = 1).pivot_table(index = ['State','District_ID'], columns = ['Race'], values='count' ,fill_value=0, aggfunc = 'sum')
dfb = df1.assign(count = 1).pivot_table(index = ['State','District_ID'], columns = ['Party'], values='count' ,fill_value=0, aggfunc = 'sum')
dfc = df2.assign(count = 1).pivot_table(index = ['State','District_ID'], columns = ['Event_Type'], values='count' ,fill_value=0, aggfunc = 'sum')
最后我们一起加入
dfa.join(dfb).join(dfc)
output
Black White Dem Ind Repub A B
State District_ID
GA 1 1 1 2 0 0 2 0
NY 2 0 1 1 0 0 0 1
SC 5 1 0 1 0 0 0 1
VA 4 1 1 0 1 1 1 0
如果第二个 dataframe 的列表由 ';' 分隔在Event Type
中,可以使用split
和explode
将其转换为原始形式:
df2 = pd.read_csv(StringIO(
"""
State District ID Event Type
0 GA 1 A; B; C
1 SC 5 B; A
2 VA 4 A; C
3 NY 2 B
4 GA 1 A; C
"""), sep='\s\s+')
df2['Event Type'] = df2['Event Type'].str.split(';')
df2.explode('Event Type')
output
State District ID Event Type
-- ------- ------------- ------------
0 GA 1 A
0 GA 1 B
0 GA 1 C
1 SC 5 B
1 SC 5 A
2 VA 4 A
2 VA 4 C
3 NY 2 B
4 GA 1 A
4 GA 1 C
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.