Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在数据帧中仅用一个数字替换另一个数字?_Python_Regex_Python 3.x_Pandas - Fatal编程技术网

Python 如何在数据帧中仅用一个数字替换另一个数字?

Python 如何在数据帧中仅用一个数字替换另一个数字?,python,regex,python-3.x,pandas,Python,Regex,Python 3.x,Pandas,我有以下数据帧: date 0 1 1 2 2 23 3 31 4 4 ... n 3 如何仅将1到9之间的所有数字替换为以下格式的一位数字: 01, 02, 03, 04, 05, 06, 07, 08, 09 我尝试使用以下功能: df['date'] = df['date'].replace(['1', '2', '3', '4', '5', '6', '7', '8', '9']),

我有以下数据帧:

   date
0   1
1   2
2   23
3   31
4   4
...
n    3
如何仅将1到9之间的所有数字替换为以下格式的一位数字:

01, 02, 03, 04, 05, 06, 07, 08, 09
我尝试使用以下功能:

df['date'] = df['date'].replace(['1', '2', '3', '4', '5', '6', '7', '8', '9']),
                                                          [' 01 ', ' 02 ', ' 03 ', '04 ', ' 05 ', ' 06 ', ' 07 ', ' 08 ', ' 09 '],regex=True)
但是,它不起作用,因为它正在修改所有的数字,即数据帧中的数字超过一位数。因此,如何规范化日期列?

尝试^[0-9]$用于模式,0\1用于替换:

>>> df = p.DataFrame(data={'date': ['1', '2', '12', '31']})
>>> df['date'].replace('^([0-9])$', r'0\1', regex=True)

0    01
1    02
2    12
3    31
Name: date, dtype: object
阅读您在其他问题上的评论,您似乎正在进行日期格式化。我认为最好用这个。下面是一个例子:

>>> from datetime import datetime
>>> df = p.DataFrame(data={'date': ['1', '2', '12', '31'], 'month': ['1', '2', '5', '12'], 'year': ['07', '10', '16', '17']})
>>> dates = df.apply(lambda row: datetime(year=2000+int(row['year']), month=int(row['month']), day=int(row['date'])), axis=1)
>>> dates

0   2007-01-01
1   2010-02-02
2   2016-05-12
3   2017-12-31
dtype: datetime64[ns]
>>> dates.apply(lambda row: row.strftime('%x'))

0    01/01/07
1    02/02/10
2    05/12/16
3    12/31/17
dtype: object
>>> dates.apply(lambda row: row.strftime('%Y-%m-%d'))

0    2007-01-01
1    2010-02-02
2    2016-05-12
3    2017-12-31
dtype: object
这样,您可以更好地控制日期格式

编辑

如果您需要对转换进行更多控制,请改为创建函数:

>>> def convert_dates(row):
...     year = row['year']
...     month = row['month']
...     day = row['date']
...     if '' in [year, month, day]:
...         return None # Don't bother with empty values 
...     year, month, day = [int(x) for x in [year, month, day]]
...     if year < 100:
...         year += 2000
...     return datetime(year, month, day)
... 
>>> df = p.DataFrame(data={'date': ['11', '2', '1', '31'], 'month': ['08', '2', '5', '12'], 'year': ['1985', '10', '16', '']})
>>> df.apply(convert_dates, axis=1)

0   1985-08-11
1   2010-02-02
2   2016-05-01
3          NaT
dtype: datetime64[ns]
尝试^[0-9]$替换图案,尝试0\1替换图案:

>>> df = p.DataFrame(data={'date': ['1', '2', '12', '31']})
>>> df['date'].replace('^([0-9])$', r'0\1', regex=True)

0    01
1    02
2    12
3    31
Name: date, dtype: object
阅读您在其他问题上的评论,您似乎正在进行日期格式化。我认为最好用这个。下面是一个例子:

>>> from datetime import datetime
>>> df = p.DataFrame(data={'date': ['1', '2', '12', '31'], 'month': ['1', '2', '5', '12'], 'year': ['07', '10', '16', '17']})
>>> dates = df.apply(lambda row: datetime(year=2000+int(row['year']), month=int(row['month']), day=int(row['date'])), axis=1)
>>> dates

0   2007-01-01
1   2010-02-02
2   2016-05-12
3   2017-12-31
dtype: datetime64[ns]
>>> dates.apply(lambda row: row.strftime('%x'))

0    01/01/07
1    02/02/10
2    05/12/16
3    12/31/17
dtype: object
>>> dates.apply(lambda row: row.strftime('%Y-%m-%d'))

0    2007-01-01
1    2010-02-02
2    2016-05-12
3    2017-12-31
dtype: object
这样,您可以更好地控制日期格式

编辑

如果您需要对转换进行更多控制,请改为创建函数:

>>> def convert_dates(row):
...     year = row['year']
...     month = row['month']
...     day = row['date']
...     if '' in [year, month, day]:
...         return None # Don't bother with empty values 
...     year, month, day = [int(x) for x in [year, month, day]]
...     if year < 100:
...         year += 2000
...     return datetime(year, month, day)
... 
>>> df = p.DataFrame(data={'date': ['11', '2', '1', '31'], 'month': ['08', '2', '5', '12'], 'year': ['1985', '10', '16', '']})
>>> df.apply(convert_dates, axis=1)

0   1985-08-11
1   2010-02-02
2   2016-05-01
3          NaT
dtype: datetime64[ns]
使用单词边界:

查找:\b\d\b 替换:0$1

使用单词边界:

查找:\b\d\b
替换:0$1

如果需要,使用astypestr将列强制转换为str,然后调用0填充这些数字:

In [13]:
df['date'] = df['date'].astype(str).str.zfill(2)
df

Out[13]:
  date
0   01
1   02
2   23
3   31
4   04
关于你的评论:

In [17]:
df['year'] = '20' + df['date']
df

Out[17]:
  date  year
0   01  2001
1   02  2002
2   23  2023
3   31  2031
4   04  2004

当列的数据类型已经是str时,上述方法有效。如果需要,请使用astypestr将列强制转换为str,然后调用0填充这些数字:

In [13]:
df['date'] = df['date'].astype(str).str.zfill(2)
df

Out[13]:
  date
0   01
1   02
2   23
3   31
4   04
关于你的评论:

In [17]:
df['year'] = '20' + df['date']
df

Out[17]:
  date  year
0   01  2001
1   02  2002
2   23  2023
3   31  2031
4   04  2004

当列的数据类型已经是str时,上面的方法可以使用regex,比如

p = re.compile(r'\b\d\b')
p.sub(lambda x: '0'+x.group(), '0 1 2 23 34 5')
## result: '00 01 02 23 34 05'

使用正则表达式,比如

p = re.compile(r'\b\d\b')
p.sub(lambda x: '0'+x.group(), '0 1 2 23 34 5')
## result: '00 01 02 23 34 05'


在熊猫数据框中?是的,就像你的代码一样,但有不同的模式。我添加了一个例子。我更新了这个答案,告诉你如何使用apply来创建一个实际的datetime对象,以便于格式化。听起来你的数据有点乱。我可能会尝试在源位置而不是在熊猫中修复数据。您可以编写一个更复杂的函数,并将apply与该函数一起使用。请参阅此答案中的我的更新。在熊猫数据框中?是的,与您的代码类似,但模式不同。我添加了一个例子。我更新了这个答案,告诉你如何使用apply来创建一个实际的datetime对象,以便于格式化。听起来你的数据有点乱。我可能会尝试在源位置而不是在熊猫中修复数据。您可以编写一个更复杂的函数,并将apply与该函数一起使用。在这个答案中看到我的更新。谢谢,我不知道这是可以做到的。。。这个解决方案很好。但是,如果我多年来都有同样的问题呢?。例如,考虑一个列23, 12, 15的年份等,然后我需要在数字的左边20个…我该怎么做呢?如果已经是str,那么你可以只做'20'+df['year']或'20'+df['year']。你能提供一个例子吗?。。。谢谢你的帮助!我忘了提到熊猫数据帧的所有一些实例都有正确的年度格式,例如2011年,当我应用字符串连接时,我会将2011年的实例重新格式化为202011。如何将其应用于只有两个数字的实例@edchumsorry忙着处理家庭事务,为了回答你的问题,我想df['year']=np.wheredf['date'].str.len==4,'20'+df['date']应该有效谢谢,我不知道这是可能的。。。这个解决方案很好。但是,如果我多年来都有同样的问题呢?。例如,考虑一个列23, 12, 15的年份等,然后我需要在数字的左边20个…我该怎么做呢?如果已经是str,那么你可以只做'20'+df['year']或'20'+df['year']。你能提供一个例子吗?。。。谢谢你的帮助!我忘了提到熊猫数据帧的所有一些实例都有正确的年度格式,例如2011年,当我应用字符串连接时,我会将2011年的实例重新格式化为202011。如何将其应用于只有两个数字的实例@edchumsorry忙于处理家庭事务,为了回答你的问题,我认为df['year']=np.wheredf['date'].str.len==4,'20'+df['date']应该有效