Python:如何快速处理列中的值
嗨,这里有一个数据帧,类似于下面的数据帧df1。数据类型为字符串Python:如何快速处理列中的值,python,pandas,dataframe,Python,Pandas,Dataframe,嗨,这里有一个数据帧,类似于下面的数据帧df1。数据类型为字符串 eye nose mouse ear 34_35_a 45_66_b 45_64_a 78_87_a 35_38_a 75_76_b 95_37_a 38_79_a 64_43_a 85_66_b 65_45_a 87_45_a 我想得到如下数据帧那样的数据帧。eye数据分为eye_x、eye_y,
eye nose mouse ear
34_35_a 45_66_b 45_64_a 78_87_a
35_38_a 75_76_b 95_37_a 38_79_a
64_43_a 85_66_b 65_45_a 87_45_a
我想得到如下数据帧那样的数据帧。eye数据分为eye_x、eye_y,其他列相同,数据类型为float
eye_x eye_y nose_x nose_y mouse_x mouse_y ear_x ear_y
34 35 45 66 45 64 78 87
35 38 75 76 95 37 38 79
64 43 85 66 65 45 87 45
到目前为止,我知道如何通过以下代码获得(x,y)值:
eye nose mouse ear
(34, 35) (45,66) (45,64) (78,87)
(35, 38) (75,76) (95,37) (38,79)
(64, 43) (85,66) (65,45) (87,45)
我将使用
stack
和apply(pd.Series)
您可以再次尝试
stack
ing和unstack
ing
v = df.stack().str.split('_', expand=True).iloc[:, :-1]
v.columns = ['x', 'y']
v = v.unstack().swaplevel(0, 1, axis=1)
v.columns = v.columns.map('_'.join)
下面是一种使用列表理解和
pd.concat
的方法
res = pd.concat([df[col].str.split('_', expand=True).iloc[:, :2].add_prefix(col) \
for col in df], axis=1).astype(int)
我将列后缀重命名作为练习
结果
eye0 eye1 nose0 nose1 mouse0 mouse1 ear0 ear1
0 34 35 45 66 45 64 78 87
1 35 38 75 76 95 37 38 79
2 64 43 85 66 65 45 87 45
解释
- 使用
和pd.concat
axis=1沿列聚合每个类别
- 按
拆分值,使用
,只取前两个分量expand=True
- 使用
转换为pd.DataFrame.astype
int
这里有3个不错的解决方案。他们有什么问题吗?谢谢,所有答案都很好。我只是想知道我会接受哪个答案。我在等待投票。如果这是一个两难选择,我有两个建议:1。根据数据计算所有解决方案的时间,并选择最快的,或2个。如果1不起作用,掷硬币;)谢谢,我会的。实际上我是用你的代码来做的。但我会尝试使用其他人的代码来进行比较。请给我一些时间,我想公平对待每一个人!
v.sort_index(axis=1)
ear_x ear_y eye_x eye_y mouse_x mouse_y nose_x nose_y
0 78 87 34 35 45 64 45 66
1 38 79 35 38 95 37 75 76
2 87 45 64 43 65 45 85 66
res = pd.concat([df[col].str.split('_', expand=True).iloc[:, :2].add_prefix(col) \
for col in df], axis=1).astype(int)
eye0 eye1 nose0 nose1 mouse0 mouse1 ear0 ear1
0 34 35 45 66 45 64 78 87
1 35 38 75 76 95 37 38 79
2 64 43 85 66 65 45 87 45
df1 = pd.concat([pd.DataFrame([dict(zip([i + '_x',i + '_y'], y.split('_')[:2])) for y in x])
for i, x in df.items()], axis=1).astype(int)
print (df1)
eye_x eye_y nose_x nose_y mouse_x mouse_y ear_x ear_y
0 34 35 45 66 45 64 78 87
1 35 38 75 76 95 37 38 79
2 64 43 85 66 65 45 87 45