【问题标题】:I want to merge 4 rows to form 1 row with 4 sub-rows in pandas Dataframe我想在 pandas Dataframe 中合并 4 行以形成 1 行和 4 个子行
【发布时间】:2020-05-20 04:23:34
【问题描述】:

This is my dataframe

我试过了,但是没用:

df1['quarter'].str.contains('/^[-+](20)$/', re.IGNORECASE).groupby(df1['quarter'])

提前致谢

【问题讨论】:

标签: python-3.x regex pandas


【解决方案1】:

您好,欢迎来到论坛!如果我正确理解了您的问题,您想每年组成小组吗?

当然,您可以简单地按年分组,因为您已经有了该专栏。

假设您没有年份列,您可以简单地按整个字符串除了季度列的最后 2 个字符进行分组。像这样(我为答案创建了一个玩具数据集):

import pandas as pd

d = {'quarter' : pd.Series(['1947q1', '1947q2', '1947q3', '1947q4','1948q1']), 
 'some_value' : pd.Series([1,3,2,4,5])}

df = pd.DataFrame(d)
df

这是我们的玩具数据框:

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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 2021-12-12
    • 2019-01-10
    • 2018-11-05
    • 1970-01-01
    • 2022-12-22
    相关资源
    最近更新 更多