Python pandas read_csv .txt file in for loop returns none element
Question:
I am trying to read from list.txt
1
2
3
4
5
Here is the code
import pandas as pd
df = pd.read_csv('sample.csv', skipinitialspace=True)
list= pd.read_csv('list.txt')
print (list)
for i in list:
df1 = df.loc[(df['ID'] == i)]
print ('-------------------------')
print (df1)
It returns
1
0 2
1 3
2 4
3 5
-------------------------
Empty DataFrame
Columns: [ID, 1st, 2nd, 3rd, 4th]
Index: []
Why is it returning ID column’s i value as none, and prints Empty Dataframe?
Answers:
The reason it is returning None
is because you are iterating over a DataFrame in a wrong way.
Have a look at this:
pandas.DataFrame.iterrows
you can convert the DataFrame values into List and then iterate through the values
df = pd.read_csv('sample.csv', skipinitialspace=True)
list = df.values.tolist()
for i in range(len(list)-1):
print(list[i])
I am trying to read from list.txt
1
2
3
4
5
Here is the code
import pandas as pd
df = pd.read_csv('sample.csv', skipinitialspace=True)
list= pd.read_csv('list.txt')
print (list)
for i in list:
df1 = df.loc[(df['ID'] == i)]
print ('-------------------------')
print (df1)
It returns
1
0 2
1 3
2 4
3 5
-------------------------
Empty DataFrame
Columns: [ID, 1st, 2nd, 3rd, 4th]
Index: []
Why is it returning ID column’s i value as none, and prints Empty Dataframe?
The reason it is returning None
is because you are iterating over a DataFrame in a wrong way.
Have a look at this:
pandas.DataFrame.iterrows
you can convert the DataFrame values into List and then iterate through the values
df = pd.read_csv('sample.csv', skipinitialspace=True)
list = df.values.tolist()
for i in range(len(list)-1):
print(list[i])