python创建函数将每一次跑出的结果以列的形式放置在dataframe中
时间: 2024-02-13 12:05:35 浏览: 32
可以创建一个函数来将结果添加到 DataFrame 中。以下是一个示例函数:
```python
import pandas as pd
def add_result_to_dataframe(result, df):
df.loc[len(df)] = [result]
```
该函数接受两个参数:结果和 DataFrame。它使用 `df.loc` 方法将结果添加为新行。可以多次调用该函数以添加多个结果。
以下是一个完整的示例,演示如何使用该函数:
```python
# create empty dataframe
df = pd.DataFrame(columns=['result'])
# define function to add result to dataframe
def add_result_to_dataframe(result, df):
df.loc[len(df)] = [result]
# call function multiple times to add results
add_result_to_dataframe(42, df)
add_result_to_dataframe('hello', df)
add_result_to_dataframe(3.14, df)
# print dataframe
print(df)
```
这将在 DataFrame 中创建一个名为 "result" 的列,并将每个结果添加为新行。输出将如下所示:
```
result
0 42
1 hello
2 3.14
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![](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)