用熊猫循环浏览列

我有示例数据框(实际数据集有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

还有另一种访问列的方法吗?

liaozhongfa 回答:用熊猫循环浏览列

我不确定您说“访问列”时的要求是什么。除了“访问”这些列之外,了解您想对这些列做些什么可能会有所帮助。

如果您想要一对经度对应的纬度列表,可以执行以下操作:

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()函数-参见here

本文链接:https://www.f2er.com/3163822.html

大家都在问