DataFrame.to_dict() 方法代码实例、
时间: 2024-05-02 21:19:48 浏览: 254
可以通过以下代码将 DataFrame 转换为字典:
```
import pandas as pd
# 创建 DataFrame
df = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['A', 'B', 'C']})
# 将 DataFrame 转换为字典
df_dict = df.to_dict()
print(df_dict)
```
输出结果如下:
```
{'col1': {0: 1, 1: 2, 2: 3}, 'col2': {0: 'A', 1: 'B', 2: 'C'}}
```
需要注意的是,to_dict() 方法默认返回的字典格式为列名为键,每列数据为值的嵌套字典。如果要将行名也包括在字典中,可以使用 orient='index' 参数:
```
df_dict = df.to_dict(orient='index')
print(df_dict)
```
输出结果如下:
```
{0: {'col1': 1, 'col2': 'A'}, 1: {'col1': 2, 'col2': 'B'}, 2: {'col1': 3, 'col2': 'C'}}
```
希望可以解决您的问题。
相关问题
plots = attachment1[['地块名称', '地块类型', '地块面积/亩 ']].to_dict('records')
`plots` 是一个DataFrame的实例,它通过 `attachment1` 数据框选择了三列:'地块名称','地块类型' 和 '地块面积/亩'。`to_dict('records')` 方法将这个子集转换成一个Python字典列表(每个字典对应一行数据),其中键是列名,值是相应的单元格值。
举个例子,假设`attachment1`的数据如下:
| 地块名称 | 地块类型 | 地块面积/亩 |
| --- | --- | --- |
| A区 | 商业 | 100 |
| B区 | 住宅 | 200 |
| C区 | 工业 | 300 |
那么,`plots` 变量将会是:
```python
[
{'地块名称': 'A区', '地块类型': '商业', '地块面积/亩': 100},
{'地块名称': 'B区', '地块类型': '住宅', '地块面积/亩': 200},
{'地块名称': 'C区', '地块类型': '工业', '地块面积/亩': 300}
]
```
你可以遍历这个列表来访问特定地块的信息,例如找到面积最大的地块:
```python
max_area_plot = max(plots, key=lambda x: x['地块面积/亩'])
print(f"面积最大的地块是 {max_area_plot['地块名称']},面积为 {max_area_plot['地块面积/亩']}/亩")
```
def get_all_file_info(cls, folder_id, df, ft): print(folder_id) cls.params["folderId"] = folder_id res = requests.get(url=cls.url, params=cls.params) js_data = json.loads(res.text)["data"] js_data_FoldersInfo: list[dict] = js_data["FoldersInfo"] js_data_FilesInfo: list[dict] = js_data["FilesInfo"] df = pd.concat([pd.DataFrame(js_data_FilesInfo), df], axis=0) ft = pd.concat([pd.DataFrame(js_data_FoldersInfo), ft], axis=0) if not js_data_FoldersInfo: return df, ft for _folder_id in pd.DataFrame(js_data_FoldersInfo).FolderId: df, ft = cls.get_all_file_info(_folder_id, df, ft) return df, ft 优化这段代码
这段代码可能存在一些可优化的地方,以下是一些可能的建议:
1. 使用适当的命名规则和注释,以提高代码可读性。
2. 尽可能避免使用递归函数,因为递归消耗大量的内存和 CPU 资源,可能导致堆栈溢出等问题。可以尝试使用迭代方式处理。
3. 避免多次使用 pd.DataFrame(),可以将列表先转换为 DataFrame,然后再使用 pd.concat() 进行合并。
4. 尽可能使用列表推导式等 Pythonic 的方法进行数据处理,以提高代码效率和可读性。
下面是一种可能的优化方案:
```python
def get_all_file_info(cls, folder_id, df, ft):
"""
获取指定文件夹及其子文件夹中的所有文件和文件夹信息
:param cls: 类实例
:param folder_id: 文件夹 ID
:param df: 文件信息 DataFrame
:param ft: 文件夹信息 DataFrame
:return: 文件信息 DataFrame 和文件夹信息 DataFrame
"""
cls.params["folderId"] = folder_id
res = requests.get(url=cls.url, params=cls.params)
js_data = json.loads(res.text)["data"]
js_data_folders: list[dict] = js_data["FoldersInfo"]
js_data_files: list[dict] = js_data["FilesInfo"]
df = pd.concat([df, pd.DataFrame(js_data_files)], axis=0)
ft = pd.concat([ft, pd.DataFrame(js_data_folders)], axis=0)
folders_to_process = js_data_folders.copy()
while folders_to_process:
folder_id = folders_to_process.pop(0)["FolderId"]
cls.params["folderId"] = folder_id
res = requests.get(url=cls.url, params=cls.params)
js_data = json.loads(res.text)["data"]
js_data_folders: list[dict] = js_data["FoldersInfo"]
js_data_files: list[dict] = js_data["FilesInfo"]
df = pd.concat([df, pd.DataFrame(js_data_files)], axis=0)
ft = pd.concat([ft, pd.DataFrame(js_data_folders)], axis=0)
folders_to_process.extend(js_data_folders)
return df, ft
```
这个优化方案使用了一个 while 循环来遍历所有的文件夹,而不是使用递归函数。同时,使用了列表推导式和 copy() 方法来简化代码。
阅读全文
相关推荐
















