[英]Concat and Merge columns with another in Pandas Dataframe
这看起来像我的 dataframe:
类型 | 猫 | 税 | 车税 | 类型税 |
---|---|---|---|---|
0 | 汽车_1 | Car_1_Rent | 西北;TAX1/Car_1 | NW;TAX1/Car_1_Rent |
1 | 汽车_2 | Car_2_Rent | 西北;TAX1/Car_2 | NW;TAX1/Car_2_Rent |
2 | 汽车_3 | Car_3_Rent | 西北;TAX1/Car_3 | NW;TAX1/Car_3_Rent |
3 | Car_4 | Car_4_Rent | 西北;TAX1/Car_4 | NW;TAX1/Car_4_Rent |
4 | 汽车_5 | Car_5_Rent | 西北;TAX1/Car_5 | NW;TAX1/Car_5_Rent |
5 | Car_6 | Car_6_Rent | 西北;TAX1/Car_6 | NW;TAX1/Car_6_Rent |
6 | 汽车_7 | Car_7_Rent | 西北;TAX1/Car_7 | NW;TAX1/Car_7_Rent |
23 | Moto_1 | Moto_1_Rent | 西北;TAX1/Moto_1 | NW;TAX1/Moto_1_Rent |
24 | Moto_2 | Moto_2_Rent | 西北;TAX1/Moto_2 | NW;TAX1/Moto_2_Rent |
25 | 摩托_3 | Moto_3_Rent | 西北;TAX1/Moto_3 | NW;TAX1/Moto_3_Rent |
26 | Moto_4 | Moto_4_Rent | 西北;TAX1/Moto_4 | NW;TAX1/Moto_4_Rent |
27 | 摩托_5 | Moto_5_Rent | 西北;TAX1/Moto_5 | NW;TAX1/Moto_5_Rent |
28 | 摩托_6 | Moto_6_Rent | 西北;TAX1/Moto_6 | NW;TAX1/Moto_6_Rent |
29 | Moto_7 | Moto_7_Rent | 西北;TAX1/Moto_7 | NW;TAX1/Moto_7_Rent |
这就是我想要实现的目标:
指数 | 猫 | 类型 |
---|---|---|
0 | 汽车_1 | 西北;TAX1/Car_1 |
1 | 汽车_2 | 西北;TAX1/Car_2 |
2 | 汽车_3 | 西北;TAX1/Car_3 |
3 | Car_4 | 西北;TAX1/Car_4 |
4 | 汽车_5 | 西北;TAX1/Car_5 |
5 | Car_6 | 西北;TAX1/Car_6 |
6 | 汽车_7 | 西北;TAX1/Car_7 |
7 | Moto_1 | 西北;TAX1/Moto_1 |
8 | Moto_2 | 西北;TAX1/Moto_2 |
9 | 摩托_3 | 西北;TAX1/Moto_3 |
10 | Moto_4 | 西北;TAX1/Moto_4 |
11 | 摩托_5 | 西北;TAX1/Moto_5 |
12 | 摩托_6 | 西北;TAX1/Moto_6 |
13 | Moto_7 | 西北;TAX1/Moto_7 |
14 | Car_1_Rent | NW;TAX1/Car_1_Rent |
15 | Car_2_Rent | NW;TAX1/Car_2_Rent |
16 | Car_3_Rent | NW;TAX1/Car_3_Rent |
17 | Car_4_Rent | NW;TAX1/Car_4_Rent |
18 | Car_5_Rent | NW;TAX1/Car_5_Rent |
19 | Car_6_Rent | NW;TAX1/Car_6_Rent |
20 | Car_7_Rent | NW;TAX1/Car_7_Rent |
21 | Moto_1_Rent | NW;TAX1/Moto_1_Rent |
22 | Moto_2_Rent | NW;TAX1/Moto_2_Rent |
23 | Moto_3_Rent | NW;TAX1/Moto_3_Rent |
24 | Moto_4_Rent | NW;TAX1/Moto_4_Rent |
25 | Moto_5_Rent | NW;TAX1/Moto_5_Rent |
26 | Moto_6_Rent | NW;TAX1/Moto_6_Rent |
27 | Moto_7_Rent | NW;TAX1/Moto_7_Rent |
我尝试了很多事情,但没有运气。
假设您的 dataframe 被命名为“d”,您是否尝试过:
a = d[['Cat', 'Car_tax']].rename(columns={'Car_tax':'Type'})
b = d[['tax','Type_tax']]].rename(columns={'Type_tax':'Type', 'tax':'Cat' })
pd.concat([a,b]).reset_index(drop=True)
new_cols = ['Cat', 'Type'] sub_1 = df[['Cat', 'Car_tax']] sub_2 = df[['tax', 'Type_tax']] sub_1.columns = sub_2.columns = new_cols result = pd.concat([sub_1, sub_2]).reset_index(drop=True)
您可以只将 append 列相互连接,不涉及合并/连接:
import pandas as pd
data = {'car1' : ['car10', 'car11'], 'car2': ['car20', 'car21'], 'car3': ['car30', 'car31'], 'car4': ['car40', 'car41']}
df = pd.DataFrame(data)
car1 = df['car1'].append(df['car2'])
car2 = df['car3'].append(df['car4'])
df2 = pd.DataFrame({'car1': car1, 'car2': car2})
df2 = df2.reset_index(drop=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.