【发布时间】:2019-06-21 16:31:29
【问题描述】:
如何使用这个 if 条件创建一个新的 DataFrame?
df = pd.DataFrame()
trips = pd.read_csv('trips.csv')
stops = pd.read_csv('stops.csv')
stop_times= pd.read_csv('stop_times.csv')
route_id = trips['route_id']
trip_id = trips['trip_id'] #deve coincidere con rip_id_stopTimes
direction_id = trips['direction_id'] # 0 -> andata, 1 -> ritorno
trip_id_stopTimes = stop_times['trip_id'] #deve coincidere con trip_id
stop_id = stop_times['stop_id'] #deve coincidere con stop_code
stop_code = stops['stop_code'] #deve coincidere con stop_id
stop_lat = stops['stop_lat']
stop_lon = stops['stop_lon']
stop_name = stops['stop_name']
#here is the problem
if str(trip_id_stopTimes) == str(trip_id) and str(stop_id) == str(stop_code):
df['NUMEROAMAT'] = route_id
df['IDVIAGGIO'] = trip_id
df['ANDATA/RITORNO'] = direction_id
df['IDVIAGGIO2'] = trip_id_stopTimes
df['IDFERMATA'] = stop_id
df['IDFERMATA2'] = stop_code
df['LATITUDINEFERMATA'] = stop_lat
df['LONGITUDINEFERMATA'] = stop_lon
df['NOMEFERMATA'] = stop_name
df.to_csv('Amat_finale.csv', index=False, encoding='utf-8')
我必须根据 if 条件创建一个新的 DataFrame。
【问题讨论】:
-
有点难以理解(参见stackoverflow.com/help/minimal-reproducible-example),但似乎
df2 = df.loc[(condition1) & (condition2) & ...]的某些变体(可能包括.copy())就足够了。 -
同意一些示例输入和输出将非常有帮助。也许您只需要对数据框进行合并,然后选择您想要的数据?
-
如果我只是执行这段代码,文件“Amat_finale.csv”是空的。我将尝试更好地解释:我想比较整个列,并仅在 if 为真的情况下创建一个新的 DataFrame。
标签: python pandas jupyter-notebook