pandas dataframe 转为py数据
时间: 2023-05-09 22:01:38 浏览: 165
将pandas dataframe转换为Python数据可以使用to_dict()函数。该函数可以将dataframe转换为字典,其中键表示dataframe中的列名,值表示dataframe中的每一行数据。默认情况下,to_dict()函数将返回一个包含所有行的字典,其中每一行都是一个字典。可以通过指定参数orient来实现不同类型的转换,例如orient='list'将结果转换为一个列表,其中包含每列的数据。
下面是一个示例代码:
import pandas as pd
# 创建一个dataframe
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': ['a', 'b', 'c']
})
# 将dataframe转换为字典,默认情况下orient='dict'
dict_data = df.to_dict()
print(dict_data)
# 将dataframe转换为列表
list_data = df.to_dict(orient='list')
print(list_data)
# 输出结果如下:
# {'A': {0: 1, 1: 2, 2: 3}, 'B': {0: 4, 1: 5, 2: 6}, 'C': {0: 'a', 1: 'b', 2: 'c'}}
# {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': ['a', 'b', 'c']}
从这个示例中,我们可以看到to_dict()函数的使用,以及如何将dataframe转换为字典或列表。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)