[英]Merge two dataframes based on new column(s) values
我有两个Dataframes
df1 = pd.DataFrame(
{
"A": ["1", "3", "22", "43"],
"B": ["6", "19", "4", "31"],
"C": ["47", "15", "8", "19"],
},
index=[0, 1, 2, 3],
)
df2 = pd.DataFrame(
{
"A": ["65", "47", "6", "13"],
"B": ["29", "5", "2", "21"],
"C": ["69", "9", "11", "80"],
},
index=[4, 5, 6, 7],
)
通过使用pandas
,最终结果应该是:
A B C Ti ID
0 1 6 47 am 01
1 3 19 15 am 01
2 22 4 8 am 01
3 43 31 19 am 01
4 65 29 69 pm 01
5 47 5 9 pm 01
6 6 2 11 pm 01
7 13 21 80 pm 01
我浏览了Pandas 文档,我正在尝试使用Dataframes
合并这两个数据pd.concat
。 代码是:
new_df = pd.concat([df1, df2], keys=['am', 'pm']).reset_index()
但是,新的Dataframe
出现了一个额外的列level_1
,我不希望它在那里:
level_0 level_1 A B C
0 am 0 1 6 47
1 am 1 3 19 15
2 am 2 22 4 8
3 am 3 43 31 19
4 pm 4 65 29 69
5 pm 5 47 5 9
6 pm 6 6 2 11
7 pm 7 13 21 80
我知道reset_index()
创建了不需要的列。 但为什么?
要使用pandas
获得相同的最终Dataframe
,还要做什么?
连接数据帧后,
new_df = pd.concat([df1, df2], keys=['am', 'pm'])
new_df
看起来像
A B C
am 0 1 6 47
1 3 19 15
2 22 4 8
3 43 31 19
pm 4 65 29 69
5 47 5 9
6 6 2 11
7 13 21 80
如果我们查看索引new_df.index
,它是一个 MultiIndex,其中第一级是键,第二级是旧索引:
MultiIndex([('am', 0),
('am', 1),
('am', 2),
('am', 3),
('pm', 4),
('pm', 5),
('pm', 6),
('pm', 7)],
)
然后首先我们可以使用rename_axis
和reset_index
重命名 MultiIndex 级别,但只从索引中删除第一个级别(然后成为具有其名称的列)。 请注意,默认情况下, reset_index
会从索引中删除所有级别。 这就是为什么您会看到在reset_index
之后添加了level_0
和level_1
列。
new_df = new_df.rename_axis(['Ti', None]).reset_index(level=0)
您可以通过使用具有所需顺序的列列表重新分配 DataFrame 来重新排列列。
cols = new_df.columns.tolist()
new_df = new_df[cols[1:]+[cols[0]]]
new_df['ID'] = '01'
Output:
A B C Ti ID
0 1 6 47 am 01
1 3 19 15 am 01
2 22 4 8 am 01
3 43 31 19 am 01
4 65 29 69 pm 01
5 47 5 9 pm 01
6 6 2 11 pm 01
7 13 21 80 pm 01
使用 reset_index() 时,它将旧索引添加为 dataframe 中的列。 您可以设置 drop = True 删除旧索引:
reset_index(drop = True)
这对我来说听起来像是一个更简单的解决方案。
df1['Ti'] = 'am'
df2['Ti'] = 'pm'
new_def = df1.append(df2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.