创建dataframe两列
时间: 2023-11-18 22:12:46 浏览: 126
要创建一个dataframe并设置两列数据,可以使用以下方法:
方法一:使用字典生成式
```
import pandas as pd
data = {
'列名1': [值1, 值2, 值3, ...],
'列名2': [值1, 值2, 值3, ...]
}
df = pd.DataFrame(data)
```
方法二:使用set_index和to_dict方法
```
import pandas as pd
df = pd.DataFrame({'列名1': [值1, 值2, 值3, ...], '列名2': [值1, 值2, 值3, ...]})
dict1 = df.set_index('列名1')['列名2'].to_dict()
```
方法三:将作为key的列设置为index,然后选取value的一列获取Series,使用内置的to_dict()函数
```
import pandas as pd
df = pd.DataFrame({'列名1': [值1, 值2, 值3, ...], '列名2': [值1, 值2, 值3, ...]})
dict2 = df.set_index('列名1')['列名2'].to_dict()
```
以上三种方法都可以创建一个包含两列数据的dataframe。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [DataFrame两列数据花式转dict](https://blog.csdn.net/qq_29410215/article/details/125764727)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* [DataFrame:两列数据生成字典](https://blog.csdn.net/qq_33489955/article/details/127881627)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文