【发布时间】:2020-10-27 22:37:06
【问题描述】:
我正在将两个 Pandas DataFrame 合并在一起,并得到“_x”和“_y”后缀。易于复制下面的示例。我尝试将, suffixes=(False, False) 添加到合并中,但它返回错误:ValueError: columns overlap but no suffix specified: Index(['f1', 'f2', 'f3'], dtype='object')。我必须在这里遗漏一些明显的东西?我理解为什么使用 join 会发生这种情况,但我没想到它会用于合并。
请忽略复制切片错误。我不知道为什么它没有在第 10 行抛出这个错误,而是在第 17 行抛出它。(如果你知道,上面有一个悬而未决的问题here!)
系统详情:
视窗 10
康达 4.8.2
Python 3.8.3
熊猫 1.0.5 py38he6e81aa_0 conda-forge
import pandas as pd
#### Build an example DataFrame for easy-to-replicate example ####
myid = [1, 1, 1, 2, 2]
myorder = [3, 2, 1, 2, 1]
y = [3642, 3640, 3632, 3628, 3608]
x = [11811, 11812, 11807, 11795, 11795]
df = pd.DataFrame(list(zip(myid, myorder, x, y)),
columns =['myid', 'myorder', 'x', 'y'])
df.sort_values(by=['myid', 'myorder'], inplace=True) #Line10
df.reset_index(drop=True, inplace=True)
display(df.style.hide_index())
### Typical analysis on existing DataFrame, Error occurs in here ####
for id in df.myid.unique():
tempdf = df[mygdf.myid == id]
tempdf.sort_values(by=['myid', 'myorder'], inplace=True) #Line17
tempdf.reset_index(drop=True, inplace=True)
for i, r in tempdf.iloc[1:].iterrows():
## in reality, calling a more complicated function here
## this is just a simple example
tempdf.loc[i, 'f1'] = tempdf.x[i-1] - tempdf.x[i]
tempdf.loc[i, 'f2'] = tempdf.y[i-1] - tempdf.y[i]
tempdf.loc[i, 'f3'] = tempdf.y[i] +2
what_i_care_about = ['myid', 'myorder', 'f1', 'f2', 'f3']
df = pd.merge(df, tempdf[what_i_care_about],
on=['myid', 'myorder'], how='outer')
del tempdf
display(df.style.hide_index())
【问题讨论】:
标签: python-3.x pandas merge