Python 3.x 将行、列值转换为dict和数据帧
这里没有 我有一个数据框Python 3.x 将行、列值转换为dict和数据帧,python-3.x,pandas,dictionary,dataframe,series,Python 3.x,Pandas,Dictionary,Dataframe,Series,这里没有 我有一个数据框people,其中name和text作为两列 name text 0 Obama Obama was the 44th president of the... 1 Trump Donald J. Trump ran as a republican... 我只需要对Obama进行一些探索性分析 obama= people[people['name'] == 'Obama'].copy() obama.text 35817 Oba
people
,其中name
和text
作为两列
name text
0 Obama Obama was the 44th president of the...
1 Trump Donald J. Trump ran as a republican...
我只需要对Obama
进行一些探索性分析
obama= people[people['name'] == 'Obama'].copy()
obama.text
35817 Obama was the 44th president of the unit...
Name: text, dtype: object
如何将文本转换为dict作为新列,以关键字作为单词,以单词计数作为值?例如: 完成后,如何将字典转换为单独的数据帧?
预期:
您可以使用collections模块中的
计数器对象:
import collections
people['dictionary'] = people.text.apply(lambda x: dict(collections.Counter(x.split())))
要将其中一个字典转换为数据帧,请执行以下操作:
dictionary = people['dictionary'][0]
pd.DataFrame(data={'word': dictionary.keys(), 'count': dictionary.values()})
您可以使用collections模块中的计数器对象:
import collections
people['dictionary'] = people.text.apply(lambda x: dict(collections.Counter(x.split())))
要将其中一个字典转换为数据帧,请执行以下操作:
dictionary = people['dictionary'][0]
pd.DataFrame(data={'word': dictionary.keys(), 'count': dictionary.values()})
第一部分就像一个符咒。第二个将dict转换为数据帧的操作继续给我带来了一个问题,“numpy.ndarray”对象不可调用。最后,我用dict(dictionary,orient=“index”)
pd.DataFrame.解决了这个问题,很有趣。我希望people['dictionary'][0]
能产生一本字典,但听起来你好像得到了一个熊猫系列。也许你使用的是不同版本的熊猫。您可以尝试使用引用的Dataframe.loc
或Dataframe.iloc
。是的,您是对的,这确实是一个系列,我对从R
移动感到困惑。我以为这就是熊猫的工作原理,但看起来好像是某个特定的版本。不管怎样,现在的问题已经解决了,我会尽快尝试你的建议。第一部分很有魅力。第二个将dict转换为数据帧的操作继续给我带来了一个问题,“numpy.ndarray”对象不可调用。最后,我用dict(dictionary,orient=“index”)
pd.DataFrame.解决了这个问题,很有趣。我希望people['dictionary'][0]
能产生一本字典,但听起来你好像得到了一个熊猫系列。也许你使用的是不同版本的熊猫。您可以尝试使用引用的Dataframe.loc
或Dataframe.iloc
。是的,您是对的,这确实是一个系列,我对从R
移动感到困惑。我以为这就是熊猫的工作原理,但看起来好像是某个特定的版本。不管怎样,现在的问题已经解决了,我将尽快尝试你的建议。