创建一个五行三列的名为df1的DataFrame数组,列名为 [states,years,pops],行名['one','two','three','four','five']; 给df1添加新列,列名为new_add,值为[7,4,5,8,2]。
时间: 2023-10-23 21:37:13 浏览: 21
好的,以下是代码实现:
```python
import pandas as pd
data = {'states': ['state1', 'state2', 'state3', 'state4', 'state5'],
'years': [2021, 2022, 2023, 2024, 2025],
'pops': [1000, 2000, 3000, 4000, 5000]}
df1 = pd.DataFrame(data, index=['one', 'two', 'three', 'four', 'five'], columns=['states', 'years', 'pops'])
df1['new_add'] = [7, 4, 5, 8, 2]
print(df1)
```
输出结果为:
```
states years pops new_add
one state1 2021 1000 7
two state2 2022 2000 4
three state3 2023 3000 5
four state4 2024 4000 8
five state5 2025 5000 2
```
相关问题
创建一个五行三列的名为df1的DataFrame数组,列名为 [states,years,pops],行名['one','two','three','four','five'];
好的,以下是代码实现:
```python
import pandas as pd
data = {'states': ['state1', 'state2', 'state3', 'state4', 'state5'],
'years': [2021, 2022, 2023, 2024, 2025],
'pops': [1000, 2000, 3000, 4000, 5000]}
df1 = pd.DataFrame(data, index=['one', 'two', 'three', 'four', 'five'], columns=['states', 'years', 'pops'])
print(df1)
```
输出结果为:
```
states years pops
one state1 2021 1000
two state2 2022 2000
three state3 2023 3000
four state4 2024 4000
five state5 2025 5000
```
2.创建一个五行三列的名为df1的DataFrame数组,列名为 [states,years,pops],行名['one','two','three','four','five'],值自定。
好的,您可以按照以下代码创建一个五行三列的名为df1的DataFrame数组,其中列名为 [states,years,pops],行名为['one','two','three','four','five']:
```
import pandas as pd
data = {'states': ['CA', 'NY', 'TX', 'FL', 'IL'],
'years': [2010, 2011, 2012, 2013, 2014],
'pops': [37, 39, 27, 26, 20]}
df1 = pd.DataFrame(data, index=['one', 'two', 'three', 'four', 'five'], columns=['states', 'years', 'pops'])
```
这里我们通过字典的形式来创建数据,每一列的数据作为字典的值,而列名则作为字典的键。在创建DataFrame时,我们指定了数据、行名和列名。您可以根据自己的需要修改数据和名称。
阅读全文