使用字符串列表将 pandas 数据框列中的每个单词小写的问题
Problems lowercasing each word in a pandas dataframe column with lists of strings
正如标题所说,我正在尝试将数据框列上的字符串列表中的每个元素小写。
我的示例:
df
A
0 [Verapamil hydrochloride]
1 [Simvastatin]
2 [Sulfamethoxazole, Trimethoprim]
我想要的示例:
df
A
0 [verapamil hydrochloride]
1 [simvastatin]
2 [sulfamethoxazole, trimethoprim]
我尝试使用:
df['A'].apply(lambda x: [w.lower() for w in x])
但它输出:
TypeError: 'float' object is not iterable
当单独检查时,它没有识别出任何浮动
type(df['A'][0])
#Out: list
type(df['A'][0][0])
#Out: str
我这样做是因为我想稍后使用set()
比较列表,因为不仅其他列表中的元素可以有小写的strings
,而且还可以更改顺序在列表中。
我真的不知道该怎么办,因为我找不到那个错误的原因。有其他选择吗?
您可以使用:
variable.lowercase()
import pandas as pd
df = pd.read_csv('DCI.csv')
df['ActiveSubstances'] = df['ActiveSubstances'].astype(str)
df['ActiveSubstances'] = df.apply(lambda row: row['ActiveSubstances'].lower(), axis=1)
print(df)
输出
ActiveSubstances
0 ['verapamil hydrochloride']
1 ['verapamil hydrochloride']
2 ['verapamil hydrochloride']
3 ['simvastatin']
4 ['simvastatin']
... ...
192520 ['doxepin hydrochloride']
192521 ['doxepin hydrochloride']
192522 ['ethosuximide']
192523 ['fludrocortisone acetate']
192524 ['sulfamethoxazole', 'trimethoprim']
[192525 rows x 1 columns]
转换为 str
然后应用 lower()
即可解决。
正如标题所说,我正在尝试将数据框列上的字符串列表中的每个元素小写。
我的示例:
df
A
0 [Verapamil hydrochloride]
1 [Simvastatin]
2 [Sulfamethoxazole, Trimethoprim]
我想要的示例:
df
A
0 [verapamil hydrochloride]
1 [simvastatin]
2 [sulfamethoxazole, trimethoprim]
我尝试使用:
df['A'].apply(lambda x: [w.lower() for w in x])
但它输出:
TypeError: 'float' object is not iterable
当单独检查时,它没有识别出任何浮动
type(df['A'][0])
#Out: list
type(df['A'][0][0])
#Out: str
我这样做是因为我想稍后使用set()
比较列表,因为不仅其他列表中的元素可以有小写的strings
,而且还可以更改顺序在列表中。
我真的不知道该怎么办,因为我找不到那个错误的原因。有其他选择吗?
您可以使用:
variable.lowercase()
import pandas as pd
df = pd.read_csv('DCI.csv')
df['ActiveSubstances'] = df['ActiveSubstances'].astype(str)
df['ActiveSubstances'] = df.apply(lambda row: row['ActiveSubstances'].lower(), axis=1)
print(df)
输出
ActiveSubstances
0 ['verapamil hydrochloride']
1 ['verapamil hydrochloride']
2 ['verapamil hydrochloride']
3 ['simvastatin']
4 ['simvastatin']
... ...
192520 ['doxepin hydrochloride']
192521 ['doxepin hydrochloride']
192522 ['ethosuximide']
192523 ['fludrocortisone acetate']
192524 ['sulfamethoxazole', 'trimethoprim']
[192525 rows x 1 columns]
转换为 str
然后应用 lower()
即可解决。