Python 熊猫数据帧自动填充
我是Python新手,我正在尝试做以下工作: 我有一个带有tweets的单列数据帧,每行包含一个tweet字符串 我可以使用df[row].split拆分任何推文的文字 但是,我找不到如何创建pd.DataFrame,其中: 它的行将是文字 它的专栏将是推文 我试着像在早期的R脚本中那样填充我的数据帧,但它不起作用Python 熊猫数据帧自动填充,python,pandas,dataframe,Python,Pandas,Dataframe,我是Python新手,我正在尝试做以下工作: 我有一个带有tweets的单列数据帧,每行包含一个tweet字符串 我可以使用df[row].split拆分任何推文的文字 但是,我找不到如何创建pd.DataFrame,其中: 它的行将是文字 它的专栏将是推文 我试着像在早期的R脚本中那样填充我的数据帧,但它不起作用 for x in range(0, len(tweets)): words[,x] = pd.DataFrame(data=tweets[x].split()) 我发现[,
for x in range(0, len(tweets)):
words[,x] = pd.DataFrame(data=tweets[x].split())
我发现[,]在数据帧中的操作与R不同,但我甚至无法找到如何在不将列指定为数组而不是定义总列数的情况下填充数据帧。到目前为止,我只成功地创建了一个单词列表
因此,我的问题如下:
在这种情况下,如何创建单词数据框?
如何通过仅指定行/列长度而不是使用数组来创建n*m数据帧?
是否有任何方法可以使用df[row].split一次提取超过1行?
这可能不是最好的解决方案,但它满足了您的需求:
import pandas as pd
import numpy as np
data = [
['This is a sentence.'],
['This is also a sentence.'],
['Hi.']
]
data = pd.DataFrame(data)
max_len = 0
for index, row in data.iterrows():
length = len(row.values[0].split())
if length > max_len:
max_len = length
words = pd.DataFrame(index=range(data.shape[0]), columns=range(max_len))
for i in range(data.shape[0]):
j = 0
for word in data.iloc[i].values[0].split():
words.iloc[i, j] = word
j += 1
print(words)
输出:
0 1 2 3 4
0 This is a sentence. NaN
1 This is also a sentence.
2 Hi NaN NaN NaN NaN
我刚刚找到了另一种类似于提议的方法:
tweets = pd.DataFrame(data.tweet)
max_words = 0
for i in range(0, len(tweets)):
if max_words < len(tweets.iloc[i,0].split()):
max_words = len(tweets.iloc[i,0].split())
words = pd.DataFrame(columns= range(len(tweets)), index= range(max_words))
for i in range(0, max_words):
words.iloc[i] = tweets.tweet.str.split().str[i]