python - 使用每个选择标准的用户输入循环遍历数据框
问题描述
我正在使用的两个数据结构是数据框和列表。我需要在索引 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 列与字典映射。也许仔细看看map方法会有所帮助。我希望总体上可以很好地理解代码。如果不是,请要求澄清。
推荐阅读
- virtual-machine - Pdump 应用程序的 DPDK-19.11 链接声明导致错误
- amazon-web-services - PySpark - partitionBy 到 S3 处理特殊字符
- sql - 从 Unidata 的视图中选择查询
- command - 翻译命令
- solr - Solr 拼写检查建议从不返回德语变音符号
- scala - Scala / specs2:找不到 AsExecution[ExecutionEnv => MatchResult[Future[AuthenticationResult]]] 类型的证据参数的隐式值
- gradle - gradle 中止时无法锁定文件哈希缓存
- google-cloud-platform - 如何在 Google Cloud 中获取 IAM 中所有成员的列表
- postgresql - 在 postgresql 中为 CROSSTAB 生成动态列?
- powerbi - Power BI 中使用动态访问令牌(密钥)进行 REST API 调用(如 HTTP GET)以读取数据的任何更好方法