pandas将多个字典遍历逐行写入一个dataframe
时间: 2023-11-27 13:53:09 浏览: 36
答案:可以使用pandas的DataFrame.from_dict()方法将多个字典转换为DataFrame,并设置orient参数为'index',然后使用append()方法逐行添加到DataFrame中。具体代码如下:
```
import pandas as pd
# 多个字典
dict1 = {'name': 'Alice', 'age': 20, 'gender': 'female'}
dict2 = {'name': 'Bob', 'age': 25, 'gender': 'male'}
dict3 = {'name': 'Cathy', 'age': 30, 'gender': 'female'}
# 转换为DataFrame
df = pd.DataFrame.from_dict([dict1, dict2, dict3], orient='index')
# 添加到DataFrame中
df_all = pd.DataFrame(columns=df.columns)
df_all = df_all.append(df, ignore_index=True)
```
这样就可以将多个字典逐行写入一个DataFrame中了。
相关问题
pandas将字典逐行写入dataframe
可以使用 pandas 的 DataFrame.from_dict() 方法将字典转换成 dataframe,并且可以设置参数 orient='index' 来逐行写入。代码示例如下:
```
import pandas as pd
my_dict = {
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]
}
df = pd.DataFrame.from_dict(my_dict, orient='index', columns=['col1', 'col2', 'col3'])
```
这样就可以将 my_dict 逐行写入 dataframe 中,并且可以指定列名。
pandas 循环一个excel 再遍历写入另一个excel 代码
可以使用 pandas 库来实现循环读取一个 Excel 文件,并将数据写入到另一个 Excel 文件中。下面是一个示例代码:
```python
import pandas as pd
# 读取需要处理的 Excel 文件
df = pd.read_excel('input.xlsx')
# 遍历 Excel 文件中的每一行数据
for index, row in df.iterrows():
# 获取需要写入的数据
data_to_write = [row['column1'], row['column2'], row['column3']]
# 将数据写入到另一个 Excel 文件中
with pd.ExcelWriter('output.xlsx', mode='a', engine='openpyxl') as writer:
pd.DataFrame([data_to_write]).to_excel(writer, sheet_name='Sheet1', header=False, index=False)
```
在上面的代码中,首先使用 `pd.read_excel` 函数读取需要处理的 Excel 文件,然后使用 `df.iterrows()` 遍历 Excel 文件中的每一行数据。在遍历每一行数据时,我们可以根据需要获取需要写入的数据。在本例中,我们假设需要将每一行数据的前三列写入到另一个 Excel 文件中。我们使用 `pd.ExcelWriter` 函数创建一个 Excel 文件写入器,并使用 `pd.DataFrame` 将数据写入到 Excel 文件中。最后,我们将写入器的 `mode` 参数设置为 `a`,这样可以在写入新数据时保留原有数据。