Python 如何使用regex和pandas创建月份和年份列
你好堆栈溢出社区 我这里有数据框Python 如何使用regex和pandas创建月份和年份列,python,pandas,datetime,Python,Pandas,Datetime,你好堆栈溢出社区 我这里有数据框 code sum of August AA 1000 BB 4000 CC 72262 所以有两列['code','sum of August'] 我必须将此数据帧转换为['month'、'year'、'code'、'sum of August']列 month year code sum of
code sum of August
AA 1000
BB 4000
CC 72262
所以有两列['code','sum of August']
我必须将此数据帧转换为['month'、'year'、'code'、'sum of August']列
month year code sum of August
8 2020 AA 1000
8 2020 BB 4000
8 2020 CC 72262
所以['sum of August']列有时被命名为['August']或['August']。有时,它也可以是[‘十一月的总和’]或[‘十一月’或[‘十一月’]
我考虑使用正则表达式提取月份名称并转换为月份编号
有人能帮我吗
提前谢谢 看起来您正在尝试将月份名称转换为数字,列可以是大写或小写。 这可能会奏效:
months = ['january','febuary','march','april','may','june','july','august','september','october','november','december']
monthNum = []#If you're using a list, just to make this run
sumOfMonths = ['sum of august','sum of NovemBer']#Just to show functionality
for sumOfMonth in sumOfMonths:
for idx, month in enumerate(months):
if month in sumOfMonth.lower():#If the column month name has any of the month keywords
monthNum.append(str(idx + 1)) #i'm just assuming that it's a list, just add the index + 1 to your variable.
我希望这有帮助!当然,这并不完全是您要做的,您可以填写变量并更改append(),如果您不使用它。您可以执行以下操作:
month = {1:'janauary',
2:'february',
3:'march',
4:'april',
5:'may',
6:'june',
7:'july',
8:'august',
9:'september',
10:'october',
11:'november',
12:'december'}
df['month']=[i for i,j in month.items() if j in str.lower(" ".join(df.columns))][0]
code sum of August month
0 AA 1000 8
1 BB 4000 8
2 CC 72262 8
假设您的数据帧被称为df。然后,您可以使用以下命令自动创建列月:
month = {1:'janauary',
2:'february',
3:'march',
4:'april',
5:'may',
6:'june',
7:'july',
8:'august',
9:'september',
10:'october',
11:'november',
12:'december'}
df['month']=[i for i,j in month.items() if j in str.lower(" ".join(df.columns))][0]
code sum of August month
0 AA 1000 8
1 BB 4000 8
2 CC 72262 8
这意味着,如果列名中以任何方式存在一个月的名称,请返回该月的编号。您可以使用字典将键存储为数字,将值存储为月份名称,因为月份将是ConstantThello@Karthik,但如何从列名中提取月份名称?这既聪明又简单。谢谢你抽出时间。