首页 > 解决方案 > 如何在 numpy 数组的列中添加标签

问题描述

如何在列中添加标签作为numpy数组的字符串

我需要这个输出

   One Two Three 
A   1,  2,  3  
B   4,  5,  6  
import numpy as np
import pandas as pd
a=pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
orient='index', columns=['one', 'two', 'three'])
print(a)

当我使用这段代码时,代码给了我正确的结果,但也给了我一个错误;我不明白。

注意:我不明白这一行

a=pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
    orient='index', columns=['one', 'two', 'three'])

我需要另一种方法来实现这一点。

输出:

    one  two  three 
A    1    2      3
B    4    5      6
C:\Users\Toufik\Anaconda3\lib\site-packages\ipykernel_launcher.py:4:
FutureWarning: from_items is deprecated. Please use
DataFrame.from_dict(dict(items), ...) instead.
DataFrame.from_dict(OrderedDict(items)) may be used to preserve the
key order.   after removing the cwd from sys.path.

标签: pythonpandasnumpy

解决方案


您收到的警告是告诉您您正在使用已弃用(将被删除)的语法。它建议您from_dict改用,例如

import numpy as np
import pandas as pd
a=pd.DataFrame.from_dict({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
},
orient='index', columns=['one', 'two', 'three'])
print(a)

这将提供您预期的输出

   one  two  three
A    1    2      3
B    4    5      6

解释

下面你说你不明白的块——</p>

a = pd.DataFrame.from_dict({
        'A': [1, 2, 3],
        'B': [4, 5, 6]
},
orient='index', columns=['one', 'two', 'three'])
print(a)

这会从我们作为第一个参数传入DataFrame的字典 ( ) 中创建一个。from_dict

{'A': [1, 2, 3], 'B': [4, 5, 6]}

这本词典有 2 个条目,“A”和“B”,每个条目都包含一个数字列表。如果您将其传递给pd.DataFrame.from_dict自己,例如

a = pd.DataFrame.from_dict({
        'A': [1, 2, 3],
        'B': [4, 5, 6]
})
print(a)

您将获得以下输出。

   A  B
0  1  4
1  2  5
2  3  6

如您所见,字典的键作为列标题输出。要将字典键用作(行)索引标题并旋转您可以传入的数据orient='index'

a = pd.DataFrame.from_dict({
        'A': [1, 2, 3],
        'B': [4, 5, 6]
}, orient='index')
print(a)

这将给出以下输出。

   0  1  2
A  1  2  3
B  4  5  6

最后一步是传入我们要使用的列标题。

a = pd.DataFrame.from_dict({
        'A': [1, 2, 3],
        'B': [4, 5, 6]
},
orient='index', columns=['one', 'two', 'three'])
print(a)

这给出了预期的输出

   one  two  three
A    1    2      3
B    4    5      6

推荐阅读