在 Pandas DataFrame 中拆分一列元组
在 Pandas DataFrame 中,将包含元组的列拆分为多列是常见操作。为了实现这一点,可以采用以下方法:
使用 pd.DataFrame(col.tolist())
该方法将元组列转换为列表元组,然后从中创建一个新的数据框。新数据帧的索引与原始数据帧的索引相匹配。
import pandas as pd
# Create a dataframe with a column containing tuples
df = pd.DataFrame({'a': [1, 2], 'b': [(1, 2), (3, 4)]})
# Split the 'b' column into 'b1' and 'b2'
df[['b1', 'b2']] = pd.DataFrame(df['b'].tolist(), index=df.index)
# Print the resulting dataframe
print(df)
输出:
a b b1 b2 0 1 (1, 2) 1 2 1 2 (3, 4) 3 4
注意:使用 df['b'].apply(pd.Series) 而不是 pd.DataFrame(df['b'].tolist(), index= df.index) 也有效。但是,它速度较慢并且需要更多内存。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3