Return Python if condition

Asked 2 years ago, Updated 2 years ago, 87 views

For example, there is a csv file in a column (here, let's call it 'name') that has very many strings, such as a, b, c, d, e, f, g, h, i...

After reading the csv file, I would like to return it to the actual condition, not to print it out by giving it an if conditional statement For example, return to = 1 if a,b,c,d in the 'name' column otherwise return to 0 I want to write a code in the csv file that is actually read, not just printed, that all the character values in the column 'name' are changed to 0 or 1. It's hard because I don't have the basics. I'd appreciate your help.

python csv

2022-09-22 14:14

1 Answers

The requirements are very strange, but I'm not sure if this is what I want.

>>> import pandas as pd
>>> df = pd.DataFrame({'name':list('abcdefghi')})
>>> df
  name
0    a
1    b
2    c
3    d
4    e
5    f
6    g
7    h
8    i
>>> df.to_csv('temp.csv', index=False)
>>> df1 = pd.read_csv('temp.csv')
>>> df1
  name
0    a
1    b
2    c
3    d
4    e
5    f
6    g
7    h
8    i
>>> # There are 'a', 'b', 'c', and 'd' among 'name'?
>>> if set(df1['name']) & set(('a', 'b', 'c', 'd')) == set(('a', 'b', 'c', 'd')):
    df1['name'] = 1
else:
    df1['name'] = 0


>>> df1
   name
0     1
1     1
2     1
3     1
4     1
5     1
6     1
7     1
8     1

>>> df1.to_csv('temp.csv', index=False)

>>> df2 = pd.read_csv('temp.csv')
>>> df2
   name
0     1
1     1
2     1
3     1
4     1
5     1
6     1
7     1
8     1
>>> 


2022-09-22 14:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.