python - 在 Python 中重新格式化 DataFrame
问题描述
以下是我拥有的数据框:
ID Char Location
1 a IN
2 b,c,d US
3 e,g IN
4 ,,, CA
下面是我想要的数据框:
ID Char Location
1 a IN
2 b US
2 c US
2 d US
3 e IN
3 g IN
4 CA
如何转换此数据框?
解决方案
尝试这个:
df = pd.DataFrame({'ID': [1,2,3,4], 'Char': ['a', 'b,c,d', 'e,g', ',,,'], 'Location': ['IN', 'US', 'IN', 'CA']})
# copy the original order of columns
org_cols = df.columns.copy()
# explode Char column
df = df.drop(columns='Char').join(df['Char'].str.split(',').apply(lambda x: list(set(x))).explode())
# reorder columns
df = df[org_cols]
df
ID Char Location
0 1 a IN
1 2 c US
1 2 b US
1 2 d US
2 3 e IN
2 3 g IN
3 4 CA
推荐阅读
- exception - Parcelable 在写入可序列化对象时遇到 IOException (name = [Lcom.example.gaeo.Model_responsable;)
- python - python对象中的并行化
- c# - UWP - 更改 MatrixTransform 的矩阵不会导致变换的更改
- django - 在两个对象的管理表单中使多对多字段可编辑
- asp.net - 尝试在 IIS 中启动我的 asp.net 应用程序池时出现部署问题
- python - Input(shape=(6,7)) 在 model.predict 上需要 3 个维度
- unity3d - 如何判断游戏中实际显示的内容?
- ios - UIDatePicker 设计中的错误
- javascript - 打字稿:如何将数字转换为 int8、int16、int32、uint8、uint16 或 uint32
- c++ - 无法使用带有 gst-launch-1.0 的 Qemu 在 armv7 上播放 wav 音频