如何使用regex和panda创建月份和年份列



Hello Stack溢出Community

我这里有数据帧

code        sum of August 
AA             1000         
BB             4000           
CC             72262          

所以有两列

我必须将此数据帧转换为[月','年','代码','八月之和']列

month    year    code    sum of August
8     2020     AA      1000
8     2020     BB      4000
8     2020     CC      72262

因此,"八月之日"一栏有时只命名为"八月"或"八月"。有时,它可以是[十一月中旬]、[十一月]或[十一月]。

我想到使用regex来提取月份名称并转换为月份编号。

有人能帮我吗?

提前感谢!

您可以执行以下操作:

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。然后,您可以使用以下命令自动创建月份列:

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

这意味着,如果某个月的名称以任何方式存在于列名中,则返回该月的编号。

看起来您正在尝试将月份名称转换为数字,列可以是大写或小写。这可能有效:

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((

最新更新