2 回答
TA贡献1842条经验 获得超12个赞
试试这个:
df.fillna('').set_index(['column1','column3']).stack().str.split('\n', expand=True).stack().unstack(-2).reset_index(-1, drop=True).reset_index()
Out[1516]:
column1 column3 column2
0 1 hello Hi
1 2 hi some
2 2 hi test
3 2 hi To
4 2 hi Work
5 3 somewhere Hiya
TA贡献1827条经验 获得超8个赞
在换行符和“取消嵌套”上拆分:
from itertools import chain
v = df.pop('column2').str.split('\n') # if this doesn't work, try r'\\n'.
df = (pd.DataFrame(df.values.repeat(v.str.len(),axis=0), columns=df.columns)
.assign(column2=list(chain.from_iterable(v)))
.sort_index(axis=1))
print(df)
column1 column2 column3
0 1 Hi hello
1 2 some hi
2 2 Test hi
3 2 To hi
4 2 Work hi
5 3 Hiya somewhere
添加回答
举报