python - 将值拆入 Pandas DataFrame 中的不同行

标签 python pandas pivot-table

我有一个数据框(如下)。我对拆开 fromto 列感兴趣。

enter image description here

我需要将 fromto 列拆分为 fromto 之间每个不同年份的多行。例如,第一行将产生类似这样的内容

enter image description here

我尝试了 pd.melt() 中的所有内容至pd.pivot_table() .

最佳答案

创建一列类似数组的对象,其中包含“从”和“到”之间的所有年份,然后 explode在那一栏上。这不是最有效的解决方案,但很简单。

示例数据

   a  b  c  d  e  from    to
0  2  9  1  7  3  1940  1945
1  5  6  2  6  1  1950  1951

代码

df['year'] = [np.arange(f,t+1) for f,t in zip(df['from'], df['to'])]
df = df.explode('year')

   a  b  c  d  e  from    to  year
0  2  9  1  7  3  1940  1945  1940
0  2  9  1  7  3  1940  1945  1941
0  2  9  1  7  3  1940  1945  1942
0  2  9  1  7  3  1940  1945  1943
0  2  9  1  7  3  1940  1945  1944
0  2  9  1  7  3  1940  1945  1945
1  5  6  2  6  1  1950  1951  1950
1  5  6  2  6  1  1950  1951  1951

关于python - 将值拆入 Pandas DataFrame 中的不同行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63166294/

相关文章:

python - 在 Matplotlib 中使用 Unicode 希腊字母

python - 在 Python 中解码一列 Base64 字符串

python - Pandas - 重采样和标准差

python-3.x - pandas DatetimeIndex 到 matplotlib x-ticks

python - 在大数据集的 pandas 数据框中搜索和替换

python - 将日期插入 DataFrame 的行中

python - Pandas 格式符号 xlsx

excel - 无法启用 "Remove data from the external data range before saving the workbook"

超过 3000 列的 mySql 动态数据透视查询

python - 为什么数据透视表中有 NaN?