python - 从 panda 数据框中读取 5 行并将其插入到另一个 panda 数据框中每行一个单元格中

标签 python pandas dataframe machine-learning

我正在从 Excel 文件中读取数据: 生成的数据帧是一个具有单列和多行的数组:

   identifier
0        6051
1         771
2        6051
3        5219
4        3667
      ...
6023      771
6024     6051
6025      772

[6026 rows x 1 columns]

我需要创建一个包含 1205 行 (6025/5) 和一列的新数据框,其中我在每行单个单元格中插入原始数据框中的 5 个值: 结果应该是这样的

   identifier
0        6051 771  6051 5219 3667
1        2578 3697 24   7865 7852
2        635  6987 2485 3658 2587
3        219  8579 2569 1478 3698
4        567  5974 6587 8752 6848
      ...
1203      981 6987 2547 369  4752
1204     5651 6987 3975 6975 3974
1205      662 6975 2354 1284 1298

[1205 rows x 1 columns]

我正在阅读原始数据框,如下所示:

file = '01-03-2010.xlsx'
require_cols = [0]


df = pd.read_excel(file, sheet_name='Folha2', usecols = require_cols)
df2 = pd.DataFrame(columns=['sentence'])

df2 是生成的数据帧。

有人可以帮忙吗? BR

最佳答案

您可以尝试以下操作。

df['group'] = df.index//5 # add extra column to hold the group value
new_df = df.groupby('group').identifier.apply(list).apply(pd.Series)
df.drop('group', axis=1) # drop the extra column that was created.
print(new_df.head())

编辑:

输入

df = pd.DataFrame(np.random.randint(0,1000,size=6026), columns=["identifier"])
df.head()

identifier
0   752
1   14
2   184
3   139
4   37

解决方案

df['group'] = df.index//5
df1 = df.groupby('group').identifier.apply(list).apply(pd.Series).fillna(0)
df1 = df1.astype('int32')
df1.head()

    0   1   2   3   4
group                   
0   752 14  184 139 37
1   716 499 902 54  565
2   74  427 939 380 244
3   651 803 97  78  492
4   169 376 737 342 616

解决方案 2:(一列包含 5 个元素的数组)

df['group'] = df.index//5
df1 = pd.DataFrame(df.groupby('group').identifier.apply(list))
df1.head()

    identifier
group   
0   [752, 14, 184, 139, 37]
1   [716, 499, 902, 54, 565]
2   [74, 427, 939, 380, 244]
3   [651, 803, 97, 78, 492]
4   [169, 376, 737, 342, 616]

关于python - 从 panda 数据框中读取 5 行并将其插入到另一个 panda 数据框中每行一个单元格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59138033/

相关文章:

python - 使用 Boto3 通过虚拟专用网关查找子网路由

python - Python 中的 Hot Deck 插补

python - "PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling ` 框架.插入 ` many times, which has poor performance."

python - Pandas DF 列标题与列不对齐

python - 如何修改数据框以便每行存储其重复行的所有数据?

r - 字典样式替换多个项目

python - 使用 Scrapy 登录和抓取网页

python - Numpy interp 不对值进行插值/外推,仅查找数据点是否高于或低于最大经验值

python - 在 pandas/matplotlib 图表上拉伸(stretch) Canvas

python - 在 Python 脚本中提升权限