我有一组与数字相对应的单词,例如:
word1, word2, word3 = 1
word4 = 2
word5, word6 = 3
word7, word8, word9 = 4
word10 = 5
我想创建一个数据框,其中有2列,一个列包含每个单词,另一列包含对应的编号,例如:
Word Number
------- -------
word1 1
word2 1
word3 1
word4 2
word5 3
word6 3
word7 4
word8 4
word9 4
word10 5
如何创建字典并使用它来创建Word键功能中的列号和相应的值
答案 0 :(得分:0)
由于问题似乎还不够清楚,所以这样做可能已经结束,但这是一种可行的方法:
__name__=='__main__'
。下面是代码示例:
import sys
import pandas as pd
word1 = word2 = word3 = 1
word4 = 2
word5 = word6 = 3
word7 = word8 = word9 = 4
word10 = 5
main_module = sys.modules['__main__']
words = [
v_name for v_name in main_module.__dict__ if v_name.startswith('word')]
# ['word1', 'word2', 'word3', 'word4', 'word5', 'word6', 'word7', 'word8', 'word9', 'word10']
numbers = [getattr(main_module, v_name) for v_name in words]
# [1, 1, 1, 2, 3, 3, 4, 4, 4, 5]
# Creating the Dict
d = {'Word': words, 'Number': numbers}
df = pd.DataFrame(data=d)
# Word Number
#0 word1 1
#1 word2 1
#2 word3 1
#3 word4 2
#4 word5 3
#5 word6 3
#6 word7 4
#7 word8 4
#8 word9 4
#9 word10 5