[英]Loop through columns with Pandas
我有示例数据框(真实数据集有 100 多列):
df =
12_longitude_1 12_latitude_1 14_longitude_2 14_latitude_2 15_longitude_3 15_latitude_3
11 12 13 14 15 16
11 12 13 14 15 16
11 12 13 14 15 16
我需要使用循环访问每一列。 所以我在这里得到了答案:
pd_out = pd.DataFrame({'zone': [], 'number': []})
max_cols = 3 # or 337 in your "real" dataset
for num in range(1, max_cols + 1):
curr_lon_name = "longitude_{}".format(num) #what should I do here
curr_lat_name = "latitude_{}".format(num) #what should I do here
#some code here
还有另一种访问列的方法吗?
当您说“访问列”时,我不确定您到底要问什么。 除了“访问”它们之外,了解您想要对这些列做什么可能会有所帮助。
如果你想要一对经度对应纬度的列表,你可以这样做:
lon_names = [i for i in df.columns if "longitude" in i]
lat_names = [i.replace("longitude", "latitude") for i in lon_names]
# Check the output
for i in range(len(lon_names)):
print("Longitude_column={}, Latitude_column={}".format(lon_names[i], lat_names[i]))
请注意,如果有不匹配的纬度/经度列,这将不起作用。 如果是这种情况,您需要从这些列表中过滤一些列名。
您可以迭代 DataFrame 列:
按列名:
for col_name in pd.columns:
print(df[col_name])
或者
通过 iteritems() function - 见这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.