python - 如何将单列中所有数据的 pandas 数据框转换为多列?

标签 python pandas

我有一个包含数据的文本文件,格式为单个列表。数据实际上是许多行和列,但格式是单列。我已将其导入 pandas 数据框,并且我想 reshape 该数据框。

这是数据列表的格式:

a1
b1
c1
d1
e1
a2
b2
c2
d2
e2
a3
b3
c3
d3
e3
etc...

所需的格式是:

"Heading 1"    "Heading 2"    "Heading 3"    "Heading 4"    "Heading 5" 
a1             b1             c1             d1             e1
a2             b2             c2             d2             e2
a3             b3             c3             d3             e3

我尝试过 pandas stack 和 unstack 函数,但没有成功。我也尝试过使用 numpy 数组,但我的数据中有数字和字符串,所以这效果不佳。

最佳答案

您可以首先创建元组列表并传递给 DataFrame 构造函数:

L = ['a1', 1, 'c1', 'd1', 'e1', 'a2', 2, 'c2', 'd2', 'e2', 'a3', 3, 'c3', 'd3', 'e3']

import itertools

#https://stackoverflow.com/a/1625013
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.zip_longest(*args, fillvalue=fillvalue)

print (list(grouper(5, L)))
[('a1', 1, 'c1', 'd1', 'e1'), ('a2', 2, 'c2', 'd2', 'e2'), ('a3', 3, 'c3', 'd3', 'e3')]

df = pd.DataFrame(list(grouper(5, L))).rename(columns = lambda x: f'Heading {x + 1}')
print (df)
  Heading 1  Heading 2 Heading 3 Heading 4 Heading 5
0        a1          1        c1        d1        e1
1        a2          2        c2        d2        e2
2        a3          3        c3        d3        e3

print (df.dtypes)
Heading 1    object
Heading 2     int64
Heading 3    object
Heading 4    object
Heading 5    object
dtype: object

第一个想法是 reshape ,但最后一个是将列转换为数字:

df = pd.DataFrame(np.array(L).reshape(-1, 5)).rename(columns = lambda x: f'Heading {x + 1}')
print (df)
  Heading 1 Heading 2 Heading 3 Heading 4 Heading 5
0        a1         1        c1        d1        e1
1        a2         2        c2        d2        e2
2        a3         3        c3        d3        e3

print (df.dtypes)

Heading 1    object
Heading 2    object <- converted to object
Heading 3    object
Heading 4    object
Heading 5    object
dtype: object

关于python - 如何将单列中所有数据的 pandas 数据框转换为多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58336537/

相关文章:

python - 尝试在 python 中将 CSV 转换为 JSON 以发布到 REST API

python - 在列表中存储两个数据帧,对其进行操作但原始 df 保持不变

python - 如何使用 Pandas 对与给定条件匹配的列中的值求和?

python - Scikit-优化如何将收敛图保存到文件

python - 如何将 "New"Python 脚本选项添加到上下文菜单?

python - 如何在 Python 中忽略词云中的某些词?

python - 在 Matplotlib 中循环创建子图?

python - 根据索引合并两个数据框,替换其他列中的匹配值

python - 名称中带有 unicode 的标签和 lxml

python - pyserial 中的 inter_byte_timeout (interCharTimeout) 是什么?