我有两个要添加文字的大熊猫系列,我想要加入以获得带有合并文字的系列。
两个系列都基于相同的索引,但是一个系列的值较少,因此加入时会导致NA值。
这是一个玩具示例:
import pandas as pd
s1 = pd.Series(['red', 'blue', 'green', 'black'], index=[1,2,3,4])
s2 = pd.Series(['large', 'small'], index=[1,3])
s1
1 red
2 blue
3 green
4 black
dtype: object
s2
1 large
3 small
dtype: object
现在,我想用分隔符将两个系列的文本连接起来以获得以下系列:
1 red,large
2 blue
3 green,small
4 black
这是我到目前为止所尝试的:
s1.str.cat(s2, sep=',')
1 red,large
2 NaN
3 green,small
4 NaN
dtype: object
NaN值,而不是第一个序列的值
s1.str.cat(s2, sep=',', na_rep='')
1 red,large
2 blue,
3 green,small
4 black,
dtype: object
尾随逗号
s1.str.cat(s2, sep=',', na_rep='').str.strip(',')
这确实有效,但是它使代码难以理解,我不想使用任何额外的代码来修复应该首先正确完成的事情!
pd.concat([s1,s2], axis=1).apply(','.join)
TypeError: sequence item 1: expected str instance, float found
pd.concat([s1,s2], axis=1).agg('|'.join, axis=1)
TypeError: sequence item 1: expected str instance, float found
由于NA值而无效。
那我该怎么做呢?
答案 0 :(得分:1)
另一个选项
s1.append(s2).groupby(level=0).agg(','.join)
1 red,large
2 blue
3 green,small
4 black
dtype: object
答案 1 :(得分:0)
一种解决方法是先在s2
上添加逗号,然后在cat
和s1
上添加na_rep=''
,例如:
print (s1.str.cat(',' + s2, na_rep=''))
1 red,large
2 blue
3 green,small
4 black
dtype: object