Python 通过循环覆盖数据帧中的数据,但不存储更改
我需要在Python 通过循环覆盖数据帧中的数据,但不存储更改,python,pandas,dataframe,Python,Pandas,Dataframe,我需要在数据框中的某些单元格中添加几个字符。当我在循环中打印xx时,值符合要求。但是,当我打印整个数据帧时,这些值保持不变: for row in df['Time from AtoC']: if ':' not in row: xx = "00:" + row # print(xx) df.at['Time from AtoC'] = xx else: df.at['Time from AtoC'] = row
数据框中的某些单元格中添加几个字符。当我在循环中打印xx
时,值符合要求。但是,当我打印整个数据帧时,这些值保持不变:
for row in df['Time from AtoC']:
if ':' not in row:
xx = "00:" + row
# print(xx)
df.at['Time from AtoC'] = xx
else:
df.at['Time from AtoC'] = row
我得到的结果是
179行数据,而我只有100行,其中一些值仍然存在
未更改(前面没有00:
看起来你想在你的时间前面加00(这是字符串),如果他们不在那里?您可以将决策逻辑放入一个函数中,然后一次将其应用于列。(作为奖励,您可以使用匿名函数(lambda)在一行中完成这一切
发布样本数据和预期输出,并避免在数据帧或列上循环。在pandas
中,可以使用df['Time from AtoC']=np进行检查。其中(df['Time from AtoC'].str.contains(':'),“00:+df['Time from AtoC'],df['Time from AtoC'])也可以检查
def add_00(time):
if ':' not in time:
return "00:" + time
return time
df['Time from AtoC'] = df['Time from AtoC'].apply(add_00)