Pandas保留前n个字符,其中n在列n中定义

2024-09-30 20:26:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个来自一个源的数据帧,其中的名称背对背重复,没有分隔符

例如:

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

我相信答案会很简单,但我无法理解。干杯


Tags: 数据in名称dfdatanamesnanout
3条回答

您可以在Names列上使用apply,然后只获取所需字符串的一部分

>>> df.assign(x=df['Names'].apply(lambda x: x[:len(x)//2]))

          Names  Scores       x
0      JakeJake      70    Jake
1  ThomasThomas      81  Thomas
2    HarryHarry      23   Harry

使用regex提取名称,使用str.len提取长度:

df["X"] = df.Names.str.extract(r"^(.+)\1$")
df["N"] = df.X.str.len()

其中正则表达式查找重复2次的任何内容的完全匹配(\1指正则表达式中的第一个捕获组)

>>> df

          Names  Scores       X  N
0      JakeJake      70    Jake  4
1  ThomasThomas      81  Thomas  6
2    HarryHarry      23   Harry  5

您可以在列Names上使用^{},如下所示:

df['X'] = df['Names'].map(lambda x: x[:len(x)//2])

结果:

print(df)

          Names  Scores       X
0      JakeJake      70    Jake
1  ThomasThomas      81  Thomas
2    HarryHarry      23   Harry

相关问题 更多 >