python创建一个函数,将每次跑出的结果以列而非行的形式放置在dataframe中
时间: 2024-02-13 15:05:35 浏览: 39
要将结果以列而非行的形式添加到 Pandas DataFrame 中,可以使用以下函数:
```python
import pandas as pd
def add_result_to_dataframe(result, df):
df[result.name] = result
```
该函数接受两个参数:结果和 DataFrame。它使用结果的名称作为新列的名称,并将结果作为新列添加到 DataFrame 中。
以下是一个完整的示例,演示如何使用该函数:
```python
# create empty dataframe
df = pd.DataFrame()
# define function to add result to dataframe
def add_result_to_dataframe(result, df):
df[result.name] = result
# call function multiple times to add results
result1 = pd.Series([42, 43, 44], name='result1')
add_result_to_dataframe(result1, df)
result2 = pd.Series(['hello', 'world', '!'], name='result2')
add_result_to_dataframe(result2, df)
result3 = pd.Series([3.14, 2.71, 1.41], name='result3')
add_result_to_dataframe(result3, df)
# print dataframe
print(df)
```
这将在 DataFrame 中创建三个名为 "result1"、"result2" 和 "result3" 的列,并将每个结果添加为新列。输出将如下所示:
```
result1 result2 result3
0 42 hello 3.14
1 43 world 2.71
2 44 ! 1.41
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)