繁体   English   中英

如何将 dataframe 列的文本拆分为多列?

[英]How to split text of a dataframe column into multiple columns?

我正在尝试从 excel 工作表中检索一个字符串并将其拆分为单词,然后将其打印或写回一个新字符串,但是当使用 pandas 检索数据并尝试拆分它时出现错误,提示 Z6A8064B5DF479455557005 不支持拆分function

excel 表中有以下行:

在此处输入图像描述

我希望 output 像这样:

在此处输入图像描述

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() function ,这是不可能的。

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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM