首页 > 解决方案 > 使用每个选择标准的用户输入循环遍历数据框

问题描述

我正在使用的两个数据结构是数据框和列表。我需要在索引 0、1、n 处打印与我的列表匹配的集群列中的行......然后我需要接受用户输入并将其提供给新列。

sample_data = {'Cluster': ['A', 'B', 'A', 'B'],
                'column2' : [21, 32, 14, 45]}
sample_dataframe = pd.DataFrame(data=sample_data)
lst = ['A', 'B']

接受用户输入后所需的数据框(y 和 n 是用户将输入的内容):

expected_output = {'cluster': ['A', 'B', 'A', 'B'],
                'column2': ['Top', 'Bottom', 'Top', 'Bottom'],
                'NEW_COLUMN' : ['y', 'n', 'y', 'n']}
expected_output = pd.DataFrame(data=expected_output)

我在想某种循环,例如:

for i in lst:
    if i == column value:
      print all rows that match 
      and take user input to form a new column

我还没能把这个逻辑放在一起。
任何帮助将不胜感激!新列的用户输入应放入与列表匹配的每一行中。例如,新数据框具有用户输入“y”,其中集群为“A”,用户输入“n”,其中集群为“B”。

标签: pythonpandasdataframeloops

解决方案


我认为这应该有效。

sample_data = {'Cluster': ['A', 'B', 'A', 'B'],
                   'column2': [21, 32, 14, 45]}
sample_dataframe = pd.DataFrame(data=sample_data)
lst = ['A', 'B']

#Create a dictionary to save the user input
input_dict = {}

for i in lst:

    #Genrate Data with right Cluster
    series = sample_dataframe[sample_dataframe['Cluster'] == i]

    #Check if Cluster from list is in Datafrmae
    if series.empty:
        continue
    else:
        print(series)
        #Get user input and store it in dictionary
        input_dict[i] = input()

#Create new Column
sample_dataframe['input'] = sample_dataframe['Cluster'].map(input_dict)
print(sample_dataframe)

为了更好地理解字典是键/值对的列表。在这种情况下,集群是键,用户输入是值。要生成新列,我只需将 Cluster 列与字典映射。也许仔细看看map方法会有所帮助。我希望总体上可以很好地理解代码。如果不是,请要求澄清。


推荐阅读