我想将方法 pd.Series.str.join()
应用于我的整个数据框
A B
[foo,bar] [1,2]
[bar,foo] [3,4]
期望的输出:
A B
foobar 12
barfoo 34
现在我使用了一个相当慢的方法:
a = [df[x].str.join('') for x in df.columns]
我试过了
df.apply(pd.Series.str.join)
和
df.agg(pd.Series.str.join)
和
df.applymap(str.join)
但它们似乎都不起作用。为了扩展问题,如何有效地将系列方法应用于整个数据框?
谢谢。
最佳答案
尝试加入
包含数值的列表时总会出现问题,这就是为什么我建议我们首先将其转换为字符串。之后,我们可以使用嵌套列表理解来解决它:
df = pd.DataFrame({'A':[['Foo','Bar'],['Bar','Foo']],'B':[[1,2],[3,4]]})
df['B'] = df['B'].map(lambda x: [str(i) for i in x])
df_new = pd.DataFrame([[''.join(x) for x in df[i]] for i in df],index=df.columns).T
正确输出:
A B
FooBar 12
BarFoo 34
关于python - 将 Pandas 系列字符串函数应用于整个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62749016/