[英]Pandas dataframe return column header linked to data value for each row
I am using pandas to read any CSV files and then insert the rows into a database. 我正在使用熊猫读取所有CSV文件,然后将行插入数据库中。 I will be doing this with SQLAlchemy.
我将使用SQLAlchemy进行此操作。
I will not know the header names or size, so it has to be dynamic. 我将不知道标题名称或大小,因此它必须是动态的。 Assume the database rules will ensure data validity.
假设数据库规则将确保数据有效性。
I am trying to map the column header to each data value. 我正在尝试将列标题映射到每个数据值。 See below my current dataframe:
参见下面我当前的数据框:
Example 1 Example 2 Example 3 Example 4
Cat Dog Mouse Horse
Cow Ant Pig Elephant
Here is my desired outputted list: 这是我想要的输出列表:
Example 1=Cat, Example 2=Dog, Example 3=Mouse, Example 4=Horse
Example 1=Cow, Example 2=Ant, Example 3=Pig, Example 4=Elephant
I have tried using zip
and iterrows
with the below code: 我尝试使用
zip
和下面的代码进行iterrows
:
for index, data in df.iterrows():
mylist.append(data.values)
myzip = zip(columns, mylist)
for z in myzip:
print(z)
but this is producing one column header per multiple values as seen below: 但这会为多个值产生一个列标题,如下所示:
('Example 1', array(['Cat', 'Dog', 'Mouse', 'Horse'], dtype=object))
('Example 2', array(['Cow', 'Ant', 'Pig', 'Elephant'], dtype=object))
Any help would be greatly appreciated as not sure what function I need to use. 任何帮助将不胜感激,因为不确定我需要使用什么功能。 I'm aware of
to_sql
but I need to create an insert statement per row. 我知道
to_sql
但是我需要为每行创建一个插入语句。 Thanks 谢谢
@giser_yugang hits the ideal solution. @giser_yugang可以找到理想的解决方案。 Pandas has inbuilt method
DataFrame.to_dict(orient='dict')
which converts the dataframe and returns a dictionary, where the key-value pair can be customized using the parameter orient
. Pandas具有内置的
DataFrame.to_dict(orient='dict')
,该方法可以转换数据帧并返回字典,在其中可以使用参数orient
自定义键值对。
'records' amongst the 'orient' gives the kind of result you want. “东方”之中的“记录”给出了您想要的结果。
So your dataframe: 因此,您的数据框:
After using: 使用后:
df.to_dict(orient='records')
gives: 得到:
[{'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.