pandas将字典逐行写入dataframe
时间: 2023-10-14 07:26:25 浏览: 33
可以使用 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将多个字典遍历逐行写入一个dataframe
答案:可以使用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中了。
python用pandas将字典数据写入excel
可以使用pandas库的DataFrame和to_excel方法将字典数据写入Excel文件。
下面是一个简单的示例代码:
```python
import pandas as pd
# 定义一个字典
data = {'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35],
'gender': ['F', 'M', 'M']}
# 将字典转换成DataFrame
df = pd.DataFrame(data)
# 将DataFrame写入Excel文件
df.to_excel('data.xlsx', index=False)
```
在这个代码中,我们首先定义了一个字典 `data`,其中包含三个键值对,每个键对应一个列表。然后使用 `pd.DataFrame` 将字典转换成DataFrame。最后使用 `to_excel` 方法将DataFrame写入Excel文件。`index=False` 表示不写入行索引。
你可以根据需要修改代码以适应你的数据格式。