合并两个pandas数据帧,只获取列标题

时间:2018-06-07 22:30:55

标签: python pandas dataframe merge

我有2个这样的df:df1

Pressure    merge_key
923.3383179 1/1/2012 0:00
923.2299805 1/1/2012 0:30
923.1216431 1/1/2012 1:00
923.1466675 1/1/2012 1:30

DF2

merge_key       value
1/1/2012 0:30   16.9444
1/1/2012 0:30   16.6837
1/1/2012 0:30   16.6837
1/1/2012 0:30   16.9444
1/1/2012 0:30   16.1623
1/1/2012 0:30   16.6837
1/1/2012 1:00   16.1623
1/1/2012 1:00   16.423
1/1/2012 1:00   16.1623
1/1/2012 1:00   17.2051
1/1/2012 1:00   16.9444
1/1/2012 1:00   16.423

尝试所有类型的合并命令,它仍然给我一个没有数据的df,除了列标题。有解决方案吗谢谢!

1 个答案:

答案 0 :(得分:1)

听起来你没有正确地从数据框中调用.merge()方法。尝试

import pandas as pd

# Your reproducible example
d1 = {'Pressure': {0: 923.3383179, 1: 923.2299805, 2: 923.1216431, 3: 923.1466675}, 'merge_key': {0: '1/1/2012 0:00', 1: '1/1/2012 0:30', 2: '1/1/2012 1:00', 3: '1/1/2012 1:30'}}
d2 = {'merge_key': {0: '1/1/2012 0:30', 1: '1/1/2012 0:30', 2: '1/1/2012 0:30', 3: '1/1/2012 0:30', 4: '1/1/2012 0:30', 5: '1/1/2012 0:30', 6: '1/1/2012 1:00', 7: '1/1/2012 1:00', 8: '1/1/2012 1:00', 9: '1/1/2012 1:00', 10: '1/1/2012 1:00', 11: '1/1/2012 1:00'}, 'value': {0: 16.9444, 1: 16.6837, 2: 16.6837, 3: 16.9444, 4: 16.1623, 5: 16.6837, 6: 16.1623, 7: 16.423, 8: 16.1623, 9: 17.2051, 10: 16.9444, 11: 16.423}}

# Convert above dictionary to pandas data frame
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)

print(df1)
#      Pressure      merge_key
# 0  923.338318  1/1/2012 0:00
# 1  923.229981  1/1/2012 0:30
# 2  923.121643  1/1/2012 1:00
# 3  923.146668  1/1/2012 1:30
print(df2)
#         merge_key    value
# 0   1/1/2012 0:30  16.9444
# 1   1/1/2012 0:30  16.6837
# 2   1/1/2012 0:30  16.6837
# 3   1/1/2012 0:30  16.9444
# 4   1/1/2012 0:30  16.1623
# 5   1/1/2012 0:30  16.6837
# 6   1/1/2012 1:00  16.1623
# 7   1/1/2012 1:00  16.4230
# 8   1/1/2012 1:00  16.1623
# 9   1/1/2012 1:00  17.2051
# 10  1/1/2012 1:00  16.9444
# 11  1/1/2012 1:00  16.4230
print(df1.merge(df2))
#       Pressure      merge_key    value
# 0   923.229981  1/1/2012 0:30  16.9444
# 1   923.229981  1/1/2012 0:30  16.6837
# 2   923.229981  1/1/2012 0:30  16.6837
# 3   923.229981  1/1/2012 0:30  16.9444
# 4   923.229981  1/1/2012 0:30  16.1623
# 5   923.229981  1/1/2012 0:30  16.6837
# 6   923.121643  1/1/2012 1:00  16.1623
# 7   923.121643  1/1/2012 1:00  16.4230
# 8   923.121643  1/1/2012 1:00  16.1623
# 9   923.121643  1/1/2012 1:00  17.2051
# 10  923.121643  1/1/2012 1:00  16.9444
# 11  923.121643  1/1/2012 1:00  16.4230