【问题标题】:Loop through columns with Pandas使用 Pandas 循环遍历列
【发布时间】:2019-11-04 20:51:55
【问题描述】:

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

还有其他方法可以访问这些列吗?

【问题讨论】:

  • for col_name, column_series in df.iteritems(): 为您提供每一栏。
  • for i ,col in df.groupby(level=0,axis=1):

标签: python pandas numpy for-loop


【解决方案1】:

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

如果你想要一对经度对应纬度的列表,你可以这样做:

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]))

请注意,如果有不匹配的纬度/经度列,这将不起作用。如果是这种情况,您需要从这些列表中过滤掉一些列名。

【讨论】:

    【解决方案2】:

    您可以迭代 DataFrame 列:

    按列名:

     for col_name in pd.columns:
            print(df[col_name])
    

    或者

    通过 iteritems() 函数 - 见here

    【讨论】:

      猜你喜欢
      • 2021-01-29
      • 2023-03-24
      • 2018-05-30
      • 2016-05-03
      • 1970-01-01
      • 2021-03-06
      • 2019-11-14
      • 2021-09-12
      • 2019-09-07
      相关资源
      最近更新 更多