简体   繁体   中英

Python 3 appending to a empty DataFrame

Fairly new to coding. I have looked at a couple of other similar questions about appending DataFrames in python but could not solve the problem.

I have the data below (CSV) in an excel xls file:

Venue Name,Cost ,Restriction,Capacity
Cinema,5,over 13,50
Bar,10,over 18,50
Restaurant,15,no restriction,25
Hotel,7,no restriction,100

I am using the code below to try to "filter" out rows which have "no restriction" under the restrictions column. The code seems to work right through to the last line ie both print statements are giving me what I would expect.

import pandas as pd
import numpy as np

my_file = pd.ExcelFile("venue data.xlsx")
mydata = my_file.parse(0, index_col = None, na_values = ["NA"])

my_new_file = pd.DataFrame()

for index in mydata.index:
    if "no restriction" in mydata.Restriction[index]:
        print (mydata.Restriction[index])
        print (mydata.loc[index:index])
        my_new_file.append(mydata.loc[index:index], ignore_index = True)

Don't loop through dataframes. It's almost never necessary.

Use:

df2 = df[df['Restriction'] != 'no restriction']

Or

df2 = df.query("Restriction != 'no restriction'")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM