How could I copy the whole line of a data frame? Using Pandas and Python
file.csv
gender;age;vaccinated
m;23;y
m;44;y
f;12;n
f;34;y
f;20;n
import pandas as pd
file = pd.read_csv("file.csv", encoding = "utf-8", sep=";")
new_df = pd.DataFrame()
for line in file:
if line['age'] < 18 and file['vaccinated'] == 'n':
# how could I copy the whole line to the new dataframe [new_df] (including the gender information)
CodePudding user response:
You can use boolean-indexing for selecting rows:
df = pd.read_csv("file.csv", encoding="utf-8", sep=";")
new_df = df[(df["age"] < 18) & (df["vaccinated"] == "n")]
print(new_df)
Prints:
gender age vaccinated
2 f 12 n
CodePudding user response:
You can do all of this with just one line of code
import pandas as pd
file = pd.read_csv("file.csv", encoding = "utf-8", sep=";")
new_df = file.query('age < 18 and vaccinated == "n"')
Here is the documentation of the .query() function
By the way, when you are looping through the file you are looping through the column names, not through the rows. So what you get is ['gender', 'age', 'vaccinated']