[英]Storing Series into a pandas DataFrame cell using apply
I have a function that returns a Series. 我有一个返回系列的函数。 I apply the function to my DataFrame using apply(), and I would like to store the resulting Series into a new column of the dataframe. 我使用apply()将函数应用于DataFrame,并且我想将生成的Series存储到dataframe的新列中。 eg, 例如,
| 1 | 2
---+---+------------------------------------
0 | 1 | <class 'pandas.core.series.Series'>
1 | 2 | <class 'pandas.core.series.Series'>
2 | 3 | <class 'pandas.core.series.Series'>
However, it seems that pandas wants to expand the series and store it into multiple columns, so I get a ValueError: Wrong number of items passed 3, placement implies 1. 但是,似乎熊猫希望扩展该系列并将其存储到多列中,所以我得到了ValueError:传递的项目数错误3,放置意味着1。
import pandas as pd
df = pd.DataFrame({1: [1, 2, 3]})
def f(x):
return pd.Series(['a', 'b', 'c'])
df[2] = df.apply(f, axis=1)
How should deal with this? 应该如何处理呢?
我不建议您将series
保存到数据框单元格中,但这是转换为对象的一种方法
df['2']=[pd.Series(['a', 'b', 'c'])]*len(df)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.