从 pandas 系列列表中删除换行符
Remove newline characters from pandas series of lists
我有一个包含两列的 pandas DataFrame
,一列包含数字的标签,另一列包含包含字符串元素的列表。
数据框:
df = pd.DataFrame({
'tags': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1},
'elements': {
0: ['\n☒', '\nANNUAL REPORT PURSUANT TO SECTION 13 OR 15(d) OF THE SECURITIES EXCHANGE ACT OF 1934 '],
1: ['', ''],
2: ['\n', '\nFor the Fiscal Year Ended June 30, 2020'],
3: ['\n', '\n'],
4: ['\n', '\nOR']
}
})
我正在尝试从列 elements
的所有列表中的任何元素中删除 \n
的所有实例,但我真的很难这样做。我的解决方案是使用嵌套循环和 re.sub()
来尝试替换它们,但它什么也没做(假设这是一个糟糕的解决方案)。这是我的尝试:
for ls in range(len(page_table.elements)):
for st in range(len(page_table.elements[i])):
page_table.elements[i][st] = re.sub('\n', '', page_table.elements[i][st])
有办法吗?
您可以 explode
and then replace
\n
值。
您可以省略 .groupby(level=0).agg(list)
以不将它们放回列表中,尽管这与原始 DataFrame 的形状不同。
df["elements"] = (
df["elements"]
.explode()
.str.replace(r"\n", "", regex=True)
.groupby(level=0)
.agg(list)
)
输出:
0 [☒, ANNUAL REPORT PURSUANT TO SECTION 13 OR 15...
1 [, ]
2 [, For the Fiscal Year Ended June 30, 2020]
3 [, ]
4 [, OR]
也可以:
df['elements'] = df['elements'].map(lambda x: [y.replace('\n', '') for y in x])
0 [☒, ANNUAL REPORT PURSUANT TO SECTION 13 OR 15...
1 [, ]
2 [, For the Fiscal Year Ended June 30, 2020]
3 [, ]
4 [, OR]
我有一个包含两列的 pandas DataFrame
,一列包含数字的标签,另一列包含包含字符串元素的列表。
数据框:
df = pd.DataFrame({
'tags': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1},
'elements': {
0: ['\n☒', '\nANNUAL REPORT PURSUANT TO SECTION 13 OR 15(d) OF THE SECURITIES EXCHANGE ACT OF 1934 '],
1: ['', ''],
2: ['\n', '\nFor the Fiscal Year Ended June 30, 2020'],
3: ['\n', '\n'],
4: ['\n', '\nOR']
}
})
我正在尝试从列 elements
的所有列表中的任何元素中删除 \n
的所有实例,但我真的很难这样做。我的解决方案是使用嵌套循环和 re.sub()
来尝试替换它们,但它什么也没做(假设这是一个糟糕的解决方案)。这是我的尝试:
for ls in range(len(page_table.elements)):
for st in range(len(page_table.elements[i])):
page_table.elements[i][st] = re.sub('\n', '', page_table.elements[i][st])
有办法吗?
您可以 explode
and then replace
\n
值。
您可以省略 .groupby(level=0).agg(list)
以不将它们放回列表中,尽管这与原始 DataFrame 的形状不同。
df["elements"] = (
df["elements"]
.explode()
.str.replace(r"\n", "", regex=True)
.groupby(level=0)
.agg(list)
)
输出:
0 [☒, ANNUAL REPORT PURSUANT TO SECTION 13 OR 15...
1 [, ]
2 [, For the Fiscal Year Ended June 30, 2020]
3 [, ]
4 [, OR]
也可以:
df['elements'] = df['elements'].map(lambda x: [y.replace('\n', '') for y in x])
0 [☒, ANNUAL REPORT PURSUANT TO SECTION 13 OR 15...
1 [, ]
2 [, For the Fiscal Year Ended June 30, 2020]
3 [, ]
4 [, OR]