【发布时间】:2020-05-08 16:21:01
【问题描述】:
我正在尝试加入两个数据帧(main_df 和 df)。
print(main_df.head())
NSA Value SA Value
Date
1975-01-31 34.531020 34.725199
1975-02-28 34.996924 35.157220
1975-03-31 35.476331 35.517737
1975-04-30 35.990021 35.874357
1975-05-31 36.581159 36.283538
print(df.head())
NSA Value SA Value
Date
1975-01-31 35.759771 35.814004
1975-02-28 35.988479 36.049432
1975-03-31 36.246270 36.255031
1975-04-30 36.543662 36.493011
1975-05-31 36.784311 36.661750
main_df = main_df.join(df)
返回以下错误:
Traceback (most recent call last):
File "C:/Users/mbsta/PycharmProjects/untitled2/tester2.py", line 181, in <module>
main_df = main_df.join(df)
File "C:\Users\mbsta\Anaconda3\envs\untitled2\lib\site-packages\pandas\core\frame.py", line 7209, in join
other, on=on, how=how, lsuffix=lsuffix, rsuffix=rsuffix, sort=sort
File "C:\Users\mbsta\Anaconda3\envs\untitled2\lib\site-packages\pandas\core\frame.py", line 7232, in _join_compat
sort=sort,
File "C:\Users\mbsta\Anaconda3\envs\untitled2\lib\site-packages\pandas\core\reshape\merge.py", line 88, in merge
return op.get_result()
File "C:\Users\mbsta\Anaconda3\envs\untitled2\lib\site-packages\pandas\core\reshape\merge.py", line 649, in get_result
ldata.items, lsuf, rdata.items, rsuf
File "C:\Users\mbsta\Anaconda3\envs\untitled2\lib\site-packages\pandas\core\reshape\merge.py", line 2026, in _items_overlap_with_suffix
"{rename}".format(rename=to_rename)
ValueError: columns overlap but no suffix specified: Index(['NSA Value', 'SA Value'], dtype='object')
在明确指定索引后尝试加入时仍然出现错误
main_df = main_df.set_index('Date').join(df.set_index('Date'))
抛出以下错误:
Traceback (most recent call last):
File "C:/Users/mbsta/PycharmProjects/untitled2/tester2.py", line 180, in <module>
main_df = main_df.set_index('Date').join(df.set_index('Date'))
File "C:\Users\mbsta\Anaconda3\envs\untitled2\lib\site-packages\pandas\core\frame.py", line 4303, in set_index
raise KeyError(f"None of {missing} are in the columns")
KeyError: "None of ['Date'] are in the columns"
我正在尝试了解连接的工作原理,但我无法弄清楚为什么它不会围绕索引(日期)连接。任何澄清将不胜感激!
【问题讨论】:
-
join沿index加入。如果您在两个数据框中都有 2 列,join应该给您 4 列。但是,您的列的名称相同,这就是导致错误的原因。您需要先重命名列,使用lsuffix/rsuffix参数,或使用pd.concat({'main': main_df, 'other': df}, axis=1)来获得MultiIndex -
@piRSquared 谢谢。这正是我想要澄清的。非常感谢。
标签: python-3.x pandas dataframe join