使用python对CSV文件进行条件合并(熊猫)
我正在尝试合并具有相同架构的使用python对CSV文件进行条件合并(熊猫),python,csv,pandas,data-processing,Python,Csv,Pandas,Data Processing,我正在尝试合并具有相同架构的=2个文件。 这些文件将包含重复的条目,但行不相同,例如: file1: store_id,address,phone 9191,9827 Park st,999999999 8181,543 Hello st,1111111111 file2: store_id,address,phone 9191,9827 Park st Apt82,999999999 7171,912 John st,87282728282 Expected output: 9191,98
=2个文件。
这些文件将包含重复的条目,但行不相同,例如:
file1:
store_id,address,phone
9191,9827 Park st,999999999
8181,543 Hello st,1111111111
file2:
store_id,address,phone
9191,9827 Park st Apt82,999999999
7171,912 John st,87282728282
Expected output:
9191,9827 Park st Apt82,999999999
8181,543 Hello st,1111111111
7171,912 John st,87282728282
如果你注意到:
91919827 Park st、9999999和91919827 Park st APT829999999
根据商店id和电话类似,但我是从文件2中找到的,因为地址更具描述性
store\u id+phone\u number
是我查找位置并查找重复项的复合主键(在上面的示例中,store\u id足以找到它,但我需要基于多个列值的键)
问题:
-我需要合并具有相同架构但具有重复行的多个CSV文件。
-其中,行级合并应具有基于行的值拾取行的特定值的逻辑。例如从文件1中提取的电话和从文件2中提取的地址。
-一个或多个列值的组合将定义行是否重复
使用pandas可以实现这一点吗?将它们粉碎在一起的一种方法是使用merge(在store\u id和number上,如果它们是索引,那么这将是一个连接而不是合并):
然后,您可以使用选择地址_y
(如果存在),否则地址_x
:
In [13]: res['address'] = res.address_y.where(res.address_y, res.address_x)
In [14]: del res['address_x'], res['address_y']
In [15]: res
Out[15]:
store_id phone address
0 9191 999999999 9827 Park st Apt82
1 8181 1111111111 543 Hello st
2 7171 87282728282 912 John st
使用concat
,groupby
,agg
,您可以编写一个agg函数来选择正确的值:
import pandas as pd
import io
t1 = """store_id,address,phone
9191,9827 Park st,999999999
8181,543 Hello st,1111111111"""
t2 = """store_id,address,phone
9191,9827 Park st Apt82,999999999
7171,912 John st,87282728282"""
df1 = pd.read_csv(io.BytesIO(t1))
df2 = pd.read_csv(io.BytesIO(t2))
df = pd.concat([df1, df2]).reset_index(drop=True)
def f(s):
loc = s.str.len().idxmax()
return s[loc]
df.groupby(["store_id", "phone"]).agg(f)
谢谢,刚刚试过。我在合并时遇到此错误:ValueError:“数组太大了。”
。另外,对于2个以上的文件,这将如何工作?我需要将res与df3合并?@zengr这很奇怪。。。要使用两个以上的帧获取它,请使用join(传递帧列表和on值)
import pandas as pd
import io
t1 = """store_id,address,phone
9191,9827 Park st,999999999
8181,543 Hello st,1111111111"""
t2 = """store_id,address,phone
9191,9827 Park st Apt82,999999999
7171,912 John st,87282728282"""
df1 = pd.read_csv(io.BytesIO(t1))
df2 = pd.read_csv(io.BytesIO(t2))
df = pd.concat([df1, df2]).reset_index(drop=True)
def f(s):
loc = s.str.len().idxmax()
return s[loc]
df.groupby(["store_id", "phone"]).agg(f)