Python 3.x 我想将4行合并成一行,在数据帧中包含4个子行
我尝试过这个,但没有成功:Python 3.x 我想将4行合并成一行,在数据帧中包含4个子行,python-3.x,regex,pandas,Python 3.x,Regex,Pandas,我尝试过这个,但没有成功: df1['quarter'].str.contains('/^[-+](20)$/', re.IGNORECASE).groupby(df1['quarter']) 提前感谢大家大家好,欢迎来到论坛!如果我没弄错你的问题,你想每年组队吗 当然,你可以简单地每年分组,因为你已经有了这个专栏 假设您没有年份列,您可以简单地按整个字符串进行分组,但季度列的最后两个字符除外。像这样(我为答案创建了一个玩具数据集): 这是我们的玩具数据框: quarter some_
df1['quarter'].str.contains('/^[-+](20)$/', re.IGNORECASE).groupby(df1['quarter'])
提前感谢大家大家好,欢迎来到论坛!如果我没弄错你的问题,你想每年组队吗 当然,你可以简单地每年分组,因为你已经有了这个专栏 假设您没有年份列,您可以简单地按整个字符串进行分组,但季度列的最后两个字符除外。像这样(我为答案创建了一个玩具数据集): 这是我们的玩具数据框:
quarter some_value
0 1947q1 1
1 1947q2 3
2 1947q3 2
3 1947q4 4
4 1948q1 5
现在,我们只需按年份分组,但我们将最后2个字符减去:
grouped = df.groupby(df.quarter.str[:-2])
for name, group in grouped:
print(name)
print(group, '\n')
输出:
1947
quarter some_value
0 1947q1 1
1 1947q2 3
2 1947q3 2
3 1947q4 4
1948
quarter some_value
4 1948q1 5
附加注释:我使用了一个始终可以应用于字符串的操作。选中此项,例如:
s = 'Hi there, Dhruv!'
#Prints the first 2 characters of the string
print(s[:2])
#Output: "Hi"
#Prints everything after the third character
print(s[3:])
#Output: "there, Dhruv!"
#Prints the text between the 10th and the 15th character
print(s[10:15])
#Output: "Dhruv"
大家好,欢迎来到论坛!如果我没弄错你的问题,你想每年组队吗 当然,你可以简单地每年分组,因为你已经有了这个专栏 假设您没有年份列,您可以简单地按整个字符串进行分组,但季度列的最后两个字符除外。像这样(我为答案创建了一个玩具数据集): 这是我们的玩具数据框:
quarter some_value
0 1947q1 1
1 1947q2 3
2 1947q3 2
3 1947q4 4
4 1948q1 5
现在,我们只需按年份分组,但我们将最后2个字符减去:
grouped = df.groupby(df.quarter.str[:-2])
for name, group in grouped:
print(name)
print(group, '\n')
输出:
1947
quarter some_value
0 1947q1 1
1 1947q2 3
2 1947q3 2
3 1947q4 4
1948
quarter some_value
4 1948q1 5
附加注释:我使用了一个始终可以应用于字符串的操作。选中此项,例如:
s = 'Hi there, Dhruv!'
#Prints the first 2 characters of the string
print(s[:2])
#Output: "Hi"
#Prints everything after the third character
print(s[3:])
#Output: "there, Dhruv!"
#Prints the text between the 10th and the 15th character
print(s[10:15])
#Output: "Dhruv"
请在这里发布您的问题(代码)。请考虑下一次添加一个可复制的熊猫例子-请在这里发布您的问题(代码)。请考虑下次再添加一个可复制的熊猫例子-像这样: