[Solved] df.loc: write data in certain rows - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: [Solved] df.loc: write data in certain rows (/thread-34068.html) |
[Solved] df.loc: write data in certain rows - ju21878436312 - Jun-28-2021 I import a text file and would like to write a comment in certain rows, which I access with df.loc. However, I get the error "# When setting, missing keys are not allowed, even with .loc:". Could someone tell me, how to avaid it? I have checked the documentation, where a similar way worked out . import pandas as pd import numpy as np df = pd.read_csv('2021-06-15_data.txt', delimiter= '\t',parse_dates=[[0, 1]], header=None, names=["Date","Time","Channel","time","0.3","0.5","1.0","3.0","5.0","10.0"]) df['Date_Time'] = df['Date_Time'] + pd.Timedelta(days = 365*20) # print types works fine print(df.head(5)) df.dtypes # iloc works fine print("iloc") df.iloc[5:7] # loc works fine print("loc") df.loc[(df['Date_Time'] >= '2021-06-10 09:51:04')&(df['Date_Time'] < '2021-06-10 09:51:26')] # create new column df['Comment']="" # write data in column 'Comment', only for certain rows creates KeyError df.loc[(df['Date_Time'] >= '2021-06-10 09:51:04')&(df['Date_Time'] < '2021-06-10 09:51:26'),df['Comment']]="zero"2021-06-15_data.txt: 15.06.2001 09:50:42 1 10 5 4 4 1 1 1 15.06.2001 09:50:53 1 10 0 0 0 0 0 0 15.06.2001 09:51:04 1 10 0 0 0 0 0 0 15.06.2001 09:51:15 1 10 0 0 0 0 0 0 15.06.2001 09:51:26 1 10 0 0 0 0 0 0 15.06.2001 09:51:37 1 10 0 0 0 0 0 0 15.06.2001 09:51:48 1 10 0 0 0 0 0 0 15.06.2001 09:51:59 1 10 0 0 0 0 0 0 15.06.2001 09:52:10 1 10 0 0 0 0 0 0 15.06.2001 09:52:21 1 10 0 0 0 0 0 0 RE: df.loc: write data in certain rows - ju21878436312 - Jun-28-2021 I found the solution: # write data in column 'Comment', only for certain rows creates KeyError df.loc[(df['Date_Time'] >= '2021-06-10 09:50:31')&(df['Date_Time'] < '2021-06-10 09:51:00'),'Comment']="zero" df |