【问题标题】:Concatenate columns of dataframe in array在数组中连接数据框的列
【发布时间】:2019-08-22 11:08:59
【问题描述】:

我正在尝试制作一个数据可视化应用程序,它引入了一个文件类型 CSV,然后选择要表示的列(不是所有列都表示),我已经有了只选择几个变量的功能,但是现在我需要将这些列加入单个数据框中才能使用,我尝试这样做:

for i  in range(0, len(data1.columns)):
    i = 0
    df = np.array(data1[data1.columns[i]])
    i +=1
    print(df)

但我只重复了同一列 numb_selection = numb_columns_dataframe(即,如果我选择 5 列,同一列返回 5 次)

如何确保每次迭代插入不同的列而不总是相同的列?

【问题讨论】:

  • 你可以使用for col in data1:遍历列名。

标签: python arrays for-loop


【解决方案1】:

重复一列的问题在i重写中。

# For example `data1.columns` is ["a", "b", "c", "d", "e"]

# Your code:

for i in range(0, len(data1.columns)):
    i = 0  # Here, in every interaction, set into 0
    print(i, data1.columns[i], sep=": ")
    i += 1

# Output:
# 0: a
# 0: a
# 0: a
# 0: a
# 0: a

i = 0 & i += 1 没用,因为你已经从range 得到了i,范围从0 到len (data1.columns)

固定版本

for i in range(0, len(data1.columns)):
   print(i, data1.columns[i], sep=": ")

# Output:
# 0: a
# 1: b
# 2: c
# 3: d
# 5: e

使用手动增量 i 加上元素迭代的版本:

# First step, iter over columns
for col in data1.columns:
    print(col)

# Output:
# a
# b
# c
# d
# e

# Step two, manual increment to obtain the list (array) index
i = 0
for col in data1.columns:
    print(i, col, sep=": ")
    i += 1

# Output:
# 0: a
# 1: b
# 2: c
# 3: d
# 5: e

知道有帮助,enumerate

函数enumerate(iterable)很适合获取索引的键和值本身。

print(list(enumerate(["Hello", "world"])))

# Output:
[
  (0, "Hello"),
  (1, "world")
]

用法:

for i, col in enumerate(data1.columns):
    print(i, col, sep=": ")

# Output:
# 0: a
# 1: b
# 2: c
# 3: d
# 5: e

【讨论】:

    【解决方案2】:

    最后我解决了它,在循环之前声明一个空列表,迭代选定的变量并将索引保​​存在这个列表中。因此,我得到了一个包含我应该用于可视化的索引的列表。

    def get_index(name):
                '''
                return the index of a column name
                '''
                for column in df.columns:
                    if column == name:
                        index = df.columns.get_loc(column)
                        return index
    
            result=[]
            for i  in range(len(selected)):
                X = get_index(selected[i])
                result.append(X)
    
            df = df[df.columns[result]]
            x = df.values
    

    其中 'selected' 是选定变量的列表(首先按列名过滤,然后获取其索引号),我不知道这是否是最优雅的方式,但效果很好。

    【讨论】:

      猜你喜欢
      • 2018-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 2022-08-20
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多