gpt4 book ai didi

python - pandas Wide_to_long 后缀参数

转载 作者:行者123 更新时间:2023-11-30 22:15:52 25 4
gpt4 key购买 nike

我对在 pandas 中使用 Wide_to_long 时的参数有疑问。有一个名为 suffix 的参数我不明白。

在文档中说:

suffix : str, default ‘\d+’

A regular expression capturing the wanted suffixes. ‘\d+’ captures numeric suffixes. Suffixes with no numbers could be specified with the negated character class ‘\D+’. You can also further disambiguate suffixes, for example, if your wide variables are of the form Aone, Btwo,.., and you have an unrelated column Arating, you can ignore the last one by specifying suffix=’(!?one|two)’

New in version 0.20.0.

问题:后缀可以用什么?

我发现有人在使用wide_to_long时使用这样的后缀:suffix='.'它有什么作用?

最佳答案

TLDR:正则表达式捕获组可用于后缀参数。

suffix 参数告诉 pandas.wide_to_long 它应该根据 stub 后面的后缀在转换中包含哪些列。

从宽到长的默认行为假设您的列用数字标记,因此例如列A1、A2、A3、A4无需指定后缀即可正常工作参数,而 Aone、Atwo、A Three、Afour 将失败。

正如所解释的,它还有各种其他用途,在极少数情况下,您的列可能是 A1、A2、A3、A4、A100,并且您不想实际包含 A100 因为它实际上与其他 A# 列无关。

以下是一些说明性示例。

import pandas as pd
df = pd.DataFrame({'id': [1,2], 'A_1': ['a', 'b'],
'A_2': ['aa', 'bb'], 'A_3': ['aaa', 'bbb'],
'A_person': ['Mike', 'Amy']})

pd.wide_to_long(df, stubnames='A_', i='id', j='num')
# A_person A_
#id num
#1 1 Mike a
#2 1 Amy b
#1 2 Mike aa
#2 2 Amy bb
#1 3 Mike aaa
#2 3 Amy bbb

由于默认行为仅考虑数字,因此'A_person' 被忽略。如果您想将其添加到转换中,则可以使用 suffix 参数。让我们告诉它我们想要数字或单词。

pd.wide_to_long(df, stubnames='A_', i='id', j='suffix', suffix='(\d+|\w+)')
# A_
#id suffix
#1 1 a
#2 1 b
#1 2 aa
#2 2 bb
#1 3 aaa
#2 3 bbb
#1 person Mike
#2 person Amy

现在,如果您的 df 开头没有数字后缀,您也可以使用 suffix 参数来解决这个问题。默认调用将会失败,因为它需要数字,但告诉它查找单词会给您带来您想要的结果。

df = pd.DataFrame({'id': [1,2], 'A_one': ['a', 'b'],
'A_two': ['aa', 'bb'], 'A_three': ['aaa', 'bbb'],
'A_person': ['Mike', 'Amy']})

pd.wide_to_long(df, stubnames='A_', i='id', j='num')
#Empty DataFrame
#Columns: [A_three, A_person, A_one, A_two, A_]
#Index: []

pd.wide_to_long(df, stubnames='A_', i='id', j='suffix', suffix='\w+')
# A_
#id suffix
#1 one a
#2 one b
#1 person Mike
#2 person Amy
#1 three aaa
#2 three bbb
#1 two aa
#2 two bb

如果您不想包含 A_person,您可以告诉后缀参数仅包含某些 stub 。

pd.wide_to_long(df, stubnames='A_', i='id', j='num', suffix='(one|two|three)')
# A_person A_
#id num
#1 one Mike a
#2 one Amy b
#1 three Mike aaa
#2 three Amy bbb
#1 two Mike aa
#2 two Amy bb

基本上,如果您可以使用正则表达式捕获它,则可以将其传递给后缀以仅使用您想要的列。

关于python - pandas Wide_to_long 后缀参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50160774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com