0

I have a DataFrame which has Date in it, where the dtype of Date is 'OBJECT'. Now, I need the column names of those which don't have the date in them. I have written code for it but at the end the column names are not getting appended into the list. I really don't know why it is not appending. Can anyone help me with this?

df=
        Date       ab   dc
    0 12-02-2020   rat  iou
    1 22-03-2021   dog  dio
    2 23-07-2020   cat  uyi

code:

valid=[]
invaild=[]
d23 = df.dropna()
for col in d23:
    if d23[col].dtype == np.object:
        for i in d23[col]:
            try:
                valid.append(pd.Timestamp(i))
            except ValueError:
                invaild.append(i)
    col_name=[]
    if valid == []:
        col_name.append(col)
        print(col_name)

it gives:

['ab']
['dc']

or if I give out of for loop then it gives empty list

[]

Where am I going wrong? Output looks like:

col_name = ['ab','dc']
Kaleba KB Keitshokile
  • 1,656
  • 1
  • 6
  • 12
Rapooram
  • 49
  • 1
  • 5
  • 1
    Take `col_name` out of the for loop maybe ? – BcK Mar 16 '21 at 22:40
  • 2
    Please supply the expected [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) (MRE). We should be able to copy and paste a contiguous block of your code, execute that file, and reproduce your problem along with tracing output for the problem points. This lets us test our suggestions against your test data and desired output. Please [include a minimal data frame](https://stackoverflow.com/questions/52413246/how-to-provide-a-reproducible-copy-of-your-dataframe-with-to-clipboard) as part of your MRE. – Prune Mar 16 '21 at 22:40
  • 2
    Show where the intermediate results differ from what you expected. Your posted code is missing at least an import, the data frame, and tracing of intermediate values. – Prune Mar 16 '21 at 22:41

1 Answers1

1

It looks like col_name

col_name=[]

needs to be defined before the loop, so that it is not being overwritten inside of the loop for each iteration.

Nike
  • 1,223
  • 2
  • 19
  • 42