python - 如何将数据框列的文本拆分为多列?

标签 python excel pandas dataframe

我正在尝试从 Excel 工作表中检索字符串并将其拆分为单词,然后打印它或将其写回到新字符串中,但是当使用 pandas 检索数据并尝试拆分它时,会出现错误,提示 dataframe does' t 支持分割功能

Excel 工作表中有这一行:

enter image description here

我期望并输出如下:

enter image description here

import numpy
import pandas as pd
df = pd.read_excel('eng.xlsx')
txt = df

x = txt.split()

print(x)


AttributeError: 'DataFrame' object has no attribute 'split'

最佳答案

那是因为您正在 DataFrame 上应用 split() 函数,而这是不可能的。

import pandas as pd
import numpy as np

def append_nan(x, max_len):
    """
    Function to append NaN value into a list based on a max length
    """
    if len(x) < max_len:
        x += [np.nan]*(max_len - len(x))
    return x

# I define here a dataframe for the example
#df = pd.DataFrame(['This is my first sentence', 'This is a second sentence with more words'])
df = pd.read_excel('your_file.xlsx', index=None, header=None)
col_names = df.columns.values.tolist()
df_output = df.copy()

# Split your strings
df_output[col_names[0]] = df[col_names[0]].apply(lambda x: x.split(' '))
# Get the maximum length of all yours sentences
max_len = max(map(len, df_output[col_names[0]]))

# Append NaN value to have the same number for all column
df_output[col_names[0]] = df_output[col_names[0]].apply(lambda x: append_nan(x, max_len))

# Create columns names and build your dataframe
column_names = ["word_"+str(d) for d in range(max_len)]
df_output = pd.DataFrame(list(df_output[col_names[0]]), columns=column_names)

# Then you can save it
df_output.to_excel('output.xlsx')

关于python - 如何将数据框列的文本拆分为多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58819435/

相关文章:

jquery - 单击 HTML 元素并生成弹出窗口

python - 在 plotly 折线图上隐藏一条线

python - 如何在其他模块上下文中执行代码

python - 为什么此日期时间字符串未转换为 Pandas 数据框中的日期时间对象?

python - 从 django 模板 'int' 或 'str' 中确定值

python - 用 BeautifulSoup 替换内部 HTML?

excel - 如何在 Excel 中使用范围变量名称

Excel 函数无法区分某些阿拉伯字母

python - 找出列中最大的数字

python - 使用 Python 3.x 在 Pandas 中使用零和常量值扩展/填充时间序列数据