[英]Find any cell values >= x in Pandas dataframe and return cell value, column header, row and neighbouring cell value
[英]Pandas dataframe return column header linked to data value for each row
我正在使用熊猫读取所有CSV文件,然后将行插入数据库中。 我将使用SQLAlchemy进行此操作。
我将不知道标题名称或大小,因此它必须是动态的。 假设数据库规则将确保数据有效性。
我正在尝试将列标题映射到每个数据值。 参见下面我当前的数据框:
Example 1 Example 2 Example 3 Example 4
Cat Dog Mouse Horse
Cow Ant Pig Elephant
这是我想要的输出列表:
Example 1=Cat, Example 2=Dog, Example 3=Mouse, Example 4=Horse
Example 1=Cow, Example 2=Ant, Example 3=Pig, Example 4=Elephant
我尝试使用zip
和下面的代码进行iterrows
:
for index, data in df.iterrows():
mylist.append(data.values)
myzip = zip(columns, mylist)
for z in myzip:
print(z)
但这会为多个值产生一个列标题,如下所示:
('Example 1', array(['Cat', 'Dog', 'Mouse', 'Horse'], dtype=object))
('Example 2', array(['Cow', 'Ant', 'Pig', 'Elephant'], dtype=object))
任何帮助将不胜感激,因为不确定我需要使用什么功能。 我知道to_sql
但是我需要为每行创建一个插入语句。 谢谢
@giser_yugang可以找到理想的解决方案。 Pandas具有内置的DataFrame.to_dict(orient='dict')
,该方法可以转换数据帧并返回字典,在其中可以使用参数orient
自定义键值对。
“东方”之中的“记录”给出了您想要的结果。
因此,您的数据框:
使用后:
df.to_dict(orient='records')
得到:
[{'Example 1': 'Cat',
'Example 2': 'Dog',
'Example 3': 'Mouse',
'Example 4': 'Horse'},
{'Example 1': 'Cow',
'Example 2': 'Ant',
'Example 3': 'Pig',
'Example 4': 'Elephant'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.