我有以下数据帧:
country capital description
Greece Athens The COUNTRY of Greece has BEAUTIFUL islands
Italy Rome The COUNTRY of Rome has BEAUTIFUL roads
我想根据大写单词拆分描述列的值。
数据帧应具有以下结构:
country capital description
Greece Athens The
COUNTRY of Greece has
BEAUTIFUL islands
Italy Rome The
COUNTRY of Rome has
BEAUTIFUL roads
然而,这是不可能的,因为我得到
The length of values does not match the length of the index
所以我想复制除描述列的值之外的所有行。基于这里的帮助,我想出了这个
df = df.loc[df.index.repeat(10)]
df['decription'] = df['description'].mask(df.index.duplicated(), '')
df = df.reset_index(drop=True)
上面的逻辑不好,因为我正在任意复制行。我认为最好的方法是根据描述值上出现的不同大写单词来复制行。请注意,上面的数据帧是在不同行上展开的整个数据帧的片段。因此,不可能事先知道有多少大写单词出现在不同的行上。也许一个,也许更多。
那么,如何在不出现上述错误的情况下为数据帧提供所需的结果呢?
您可以使用Series.str.findall
并传递regex
,以使用前瞻断言查找以大写字母或行尾字符$
结尾的所有子字符串,然后explode
使其具有多行。除此之外,如果您愿意,还可以设置索引
df['description'] = df['description'].str.findall('([A-Z].*?)(?=s[A-Z][A-Z]+|$)')
df.explode('description').set_index(['country', 'capital'])
输出:
description
country capital
Greece Athens The
Athens COUNTRY of Greece has
Athens BEAUTIFUL islands
Italy Rome The
Rome COUNTRY of Rome has
Rome BEAUTIFUL roads