python - 如何在 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.
解决方案
您收到的警告是告诉您您正在使用已弃用(将被删除)的语法。它建议您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
推荐阅读
- postgresql - Oracle DBMS_UTILITY.FORMAT_CALL_STACK 和 DBMS_UTILITY.FORMAT_ERROR_STACK 的 Postgres 替代品
- python - 带有硒离开按钮的网页抓取不可点击
- typo3 - 无法翻译 TYPO3 版本 10 中的内容
- scrapy - 在 HomePage + 其他提取的链接上制作 CrawlSpider Process 数据
- sql - 查询以从多个打孔中派生计划
- mysql - 使用 python(flask) 更新 MySQL 中的最后一个条目
- python - 来自:无法阅读 /var/mail/docx
- c - strlen 和 strcpy 函数冲突
- python - python中的protobuf grpc相对导入路径差异
- internet-explorer-11 - IE 为 Angular 网站提供 ChunLoadError