Python 连接dataframe列中的所有字符串
我想将dataframe列中的所有字符串转换为单个空字符串,然后将其转换为单词列表:Python 连接dataframe列中的所有字符串,python,pandas,Python,Pandas,我想将dataframe列中的所有字符串转换为单个空字符串,然后将其转换为单词列表: import pandas as pd df = pd.DataFrame({'read': ["Red", "is", "my", "favorite", "color"]}) print(df) read 0 Red 1 is 2 my 3 favorite 4 color 我试图连接字符串,但我不知道如何添加空间 string = "" for i,j in df.iterr
import pandas as pd
df = pd.DataFrame({'read': ["Red", "is", "my", "favorite", "color"]})
print(df)
read
0 Red
1 is
2 my
3 favorite
4 color
我试图连接字符串,但我不知道如何添加空间
string = ""
for i,j in df.iterrows():
string += j["read"]
输出:
'Redismyfavoritecolor'
所需输出:
"Red is my favorite color"
使用带空格的
join
:
out = ' '.join(df["read"])
print (out)
Red is my favorite color
当我在数据帧中尝试时,得到一个类型错误。它表示预期的str实例,但得到float。如何修复它?@sai_636-如何工作
'.join(df[“read”].astype(str))
或'.join(df[“read”].dropna())
如果float
值是NaN
stthis code'.join(df[“read”].astype(str)),这就修复了它。这行在加入之前是否将所有值转换为字符串?@sai_636确切地说,它将值转换为字符串。