Python 在新版本的pandas中的单元格中追加到列表
此代码适用于Python 在新版本的pandas中的单元格中追加到列表,python,pandas,Python,Pandas,此代码适用于pandas0.23.4版,但在0.25.1版及更高版本中引发错误 import numpy as np import pandas as pd df = pd.DataFrame({'a':[1,2,3], 'b': [[0,1], [5], [10]]}) df a b 0 1 [0, 1] 1 2 [5] 2 3 [10] # both lines below throw an error in newer versions df['b
pandas
0.23.4版,但在0.25.1版及更高版本中引发错误
import numpy as np
import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b': [[0,1], [5], [10]]})
df
a b
0 1 [0, 1]
1 2 [5]
2 3 [10]
# both lines below throw an error in newer versions
df['b'] += [42]
df.loc[df['a']==3, 'b'] += [73]
df
# desired output that works in 0.23.4
a b
0 1 [0, 1, 42]
1 2 [5, 42]
2 3 [10, 42, 73]
“附加到单元格中的列表”在以后版本的pandas上是如何工作的?这里有两种方法:
方法1
df['b'] = pd.concat([df['b'], pd.Series(42)], axis=1)['b']
df.loc[df['a']==3, 'b'] = df.loc[df['a']==3, 'b'].to_numpy().tolist()[0] + [73]
方法2
from itertools import zip_longest
ls = list(zip_longest(df['b'], [42]))
df['b'] = [x[0] for x in ls]
print(df)
a b
0 1 [0, 1, 42]
1 2 [5, 42]
2 3 [10, 42]
试一试
(在pandas版本1.0.5上测试)这是一个已知的问题,请参见:我确信
lambda
会更慢,但一些快速测试表明它实际上更快。回答得很好。
df['b'].apply(lambda x: x.append(42))
df.loc[df['a']==3, 'b'].apply(lambda x: x.append(73))