我有一个来自一个源的数据帧,其中的名称背对背重复,没有分隔符
例如:
In [1]
data = {"Names": ["JakeJake", "ThomasThomas", "HarryHarry"],
"Scores": [70, 81, 23]}
df = pd.DataFrame(data)
Out [1]
Names Scores
0 JakeJake 70
1 ThomasThomas 81
2 HarryHarry 23
我希望有一个方法只保留“Names”列的前半部分。我最初的想法是这样做:
In [2]
df["N"] = df["Names"].str.len()//2
df["X"] = df["Names"].str[:df["N"]]
然而,这给出了输出
Out [2]
Names Scores N X
0 JakeJake 70 4 nan
1 ThomasThomas 81 6 nan
2 HarryHarry 23 5 nan
期望的输出是
Out [2]
Names Scores N X
0 JakeJake 70 4 Jake
1 ThomasThomas 81 6 Thomas
2 HarryHarry 23 5 Harry
我相信答案会很简单,但我无法理解。干杯
您可以在
Names
列上使用apply
,然后只获取所需字符串的一部分使用regex提取名称,使用
str.len
提取长度:其中正则表达式查找重复2次的任何内容的完全匹配(
\1
指正则表达式中的第一个捕获组)您可以在列} ,如下所示:
Names
上使用^{结果:
相关问题 更多 >
编程相关推荐