循环遍历带有用户输入的每个选择条件的数据框



我正在使用的两个数据结构是数据框架和列表。我需要从集群列中打印与索引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"。

我想应该可以。

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是键,用户输入是值。要生成新的Column,只需将Cluster列映射到字典中。也许仔细研究一下地图方法会有所帮助。我希望总的来说,代码可以很好地理解。如果没有,请要求澄清。

最新更新