Python 如何用另一个dataframe元素替换dataframe元素
我准备的数据框架如下 索引和标题 指数 1 aa aa aa 1. 1.2 bbbbbbbbbbbbbbbb 1.2 1.2.3 ccc CCCC 1.2.3 2滴滴涕滴滴涕滴滴涕滴滴涕滴滴涕滴滴涕 2.Python 如何用另一个dataframe元素替换dataframe元素,python,pandas,dataframe,Python,Pandas,Dataframe,我准备的数据框架如下 索引和标题 指数 1 aa aa aa 1. 1.2 bbbbbbbbbbbbbbbb 1.2 1.2.3 ccc CCCC 1.2.3 2滴滴涕滴滴涕滴滴涕滴滴涕滴滴涕滴滴涕 2. 如果需要将两列替换为,请使用轴为1的lambda函数: df['Title'] = df.apply(lambda x: x['Index and Title'].replace(x['Index'],''), axis=1).str.strip() 如果只需要带空格的字母(没有替换为索引列
如果需要将两列替换为
,请使用轴为1的lambda函数:
df['Title'] = df.apply(lambda x: x['Index and Title'].replace(x['Index'],''), axis=1).str.strip()
如果只需要带空格的字母(没有替换为索引
列),请使用:
由于您只展示了样本,这可能是熊猫的功能所造成的,请尝试以下内容
df["Title"] = df["Index and Title"].str.extract(r'^\d+(?:(?:\.\d+){1,})?\s+(\D+)$', expand=True)
或者,如果以后的值后面可能有数字,请尝试以下操作:
df["Title"] = df["Index and Title"].str.extract(r'^\d+(?:(?:\.\d+){1,})?\s+(.*)$', expand=True)
df
的输出如下:
Index and Title Index Title
0 1 aa aa aaaa 1 aa aa aaaa
1 1.2 bb bbbb bb bbbb bb b 1.2 bb bbbb bb bbbb bb b
2 1.2.3 ccc cc c ccccc cccccc 1.2.3 ccc cc c ccccc cccccc
3 2 dddd d d dd ddd 2 dddd d d dd ddd
说明:添加上述内容的详细说明
^\d+(?:(?:\.\d+){1,})? ##Matching starting digits in column Index and Title, digits may followed by dot and digits(1 or more occurrences) keeping this optional.
\s+ ##Matching 1 or more occurrences of spaces here.
(\D+)$ ##Creating 1st capturing group which has all non digits values till end of value.
很抱歉,我的解释太短了。”“标题”包括上面修改过的表中的空格。不用担心。我修正了我的答案。很抱歉,我的解释太短了Title'包含如上修改表所示的空格。@aaaa0a-这两种解决方案应该都能正常工作。
df["Title"] = df["Index and Title"].str.extract(r'^\d+(?:(?:\.\d+){1,})?\s+(.*)$', expand=True)
Index and Title Index Title
0 1 aa aa aaaa 1 aa aa aaaa
1 1.2 bb bbbb bb bbbb bb b 1.2 bb bbbb bb bbbb bb b
2 1.2.3 ccc cc c ccccc cccccc 1.2.3 ccc cc c ccccc cccccc
3 2 dddd d d dd ddd 2 dddd d d dd ddd
^\d+(?:(?:\.\d+){1,})? ##Matching starting digits in column Index and Title, digits may followed by dot and digits(1 or more occurrences) keeping this optional.
\s+ ##Matching 1 or more occurrences of spaces here.
(\D+)$ ##Creating 1st capturing group which has all non digits values till end of value.