[英]How to use the item price as the text frequency in a wordcloud?
我有以下數據框,需要使用 wordcloud 在 python 中進行分析:
Category Price
Dog 500
Cow 1000
Goat 650
import pandas as pd
df = pd.DataFrame({'Category': ['Dog', 'Cow', 'Goat'], 'Price': [500, 1000, 650] })
我如何編寫代碼以使“Cow”是最大的文本,其次是“Goat”等。我嘗試創建 2 個數組:Category 和 Price,然后將兩者相乘並將結果用作文本。 但是,結果數組是“DogDogDog...”和“Goatgoatgoat”,這不是我想要的。 請協助。
您需要添加一個額外的空格,以便將單詞分開。
import pandas as pd
df = pd.DataFrame({'Category': ['Dog', 'Cow', 'Goat'], 'Price': [3, 4, 5] })
text = ''
for index, row in df.iterrows():
text += (row['Category'] + ' ') * row['Price']
print(text)
輸出:
Dog Dog Dog Cow Cow Cow Cow Goat Goat Goat Goat Goat
這是一個更擴展的示例:
import pandas as pd
from matplotlib import pyplot as plt
from wordcloud import WordCloud
df = pd.DataFrame({'Category': ['Apple', 'Pear', 'Lemon', 'Pineapple', 'Nut', 'Banana', 'Grape', 'Orange', 'Plum' ],
'Price': [500, 1000, 650, 800, 3000, 900, 1100, 900, 1400 ]})
text = ''
for row in df.itertuples():
text += (row.Category + ' ') * row.Price
wordcloud = WordCloud(
width=800,height=800,
min_font_size = 10,
background_color='gold',
collocations=False
).generate(text)
# plot the WordCloud image
plt.figure(figsize = (8, 8), facecolor=None)
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.tight_layout(pad = 0)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.