我有一个数据框 df
col1 col2 col3
a;b;c w;x 1
d;e;f x;y 2
g;h;i z;u;v 3
我想将 col1
和 col2
列中的每个字符串拆分为单独的记录,以便数据框看起来像这样
col1 col2 col3
a w 1
b x 1
c NaN 1
d x 2
e y 2
f NaN 2
g z 3
h u 3
i v 3
最佳答案
尝试组合 Series.str.split
, Series.stack
, Series.rename
, pandas.concat
, DataFrame.assign
和 DataFrame.reset_index
像这样:
例子
df = pd.DataFrame([{'col1': 'a;b;c', 'col2': 'w;x', 'col3': 1}, {'col1': 'd;e;f', 'col2': 'x;y', 'col3': 2}, {'col1': 'g;h;i', 'col2': 'z;u;v', 'col3': 3}, {'col1': '1,2,3', 'col2': '2', 'col3': 4}])
print(df)
# col1 col2 col3
# 0 a;b;c w;x 1
# 1 d;e;f x;y 2
# 2 g;h;i z;u;v 3
# 3 1,2,3 2 4
df_new = (pd.concat([df[x].str.split('[;,]', expand=True).stack().rename(x)
for x in df[['col1', 'col2']]], axis=1)
.reset_index(level=1, drop=True)
.assign(col3=df.col3))
print(df_new)
col1 col2 col3
0 a w 1
0 b x 1
0 c NaN 1
1 d x 2
1 e y 2
1 f NaN 2
2 g z 3
2 h u 3
2 i v 3
3 1 2 4
3 2 NaN 4
3 3 NaN 4
关于python - Pandas 将列中的字符串拆分为多条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55713309/