Python 根据中列表列中的条件创建新列
我有一个包含列表列的数据框:Python 根据中列表列中的条件创建新列,python,pandas,Python,Pandas,我有一个包含列表列的数据框: col_1 [A, A, A, B, C] [D, B, C] [C] [A, A, A] NaN 我想创建一个新列,如果列表以3*A开始,则返回1,如果不返回0: col_1 new_col [A, A, A, B, C] 1 [D, B, C] 0 [C] 0 [A, A, A] 1 NaN
col_1
[A, A, A, B, C]
[D, B, C]
[C]
[A, A, A]
NaN
我想创建一个新列,如果列表以3*A开始,则返回1,如果不返回0:
col_1 new_col
[A, A, A, B, C] 1
[D, B, C] 0
[C] 0
[A, A, A] 1
NaN 0
我试过了,但没有成功:
df['new_col'] = df.loc[df.col_1[0:3] == [A, A, A]]
因为存在一些非列表值,所以可以使用if-else
lambda函数作为0
if-not-list:
print (df['col_1'].map(type))
0 <class 'list'>
1 <class 'list'>
2 <class 'list'>
3 <class 'list'>
4 <class 'float'>
Name: col_1, dtype: object
通过apply lambda解决方案:
df = pd.DataFrame({
'col_1': [
['A', 'A', 'A', 'B', 'C'],
['D', 'B', 'C'],
['C'],
['A', 'A', 'A']
]
})
df['new_col'] = df.col_1.apply(lambda x: x[0:3] == ['A', 'A', 'A'] if isinstance(x, list) else False).view('i1')
df.head()
输出:
下面是另一个使用map
的潜在解决方案:
import pandas as pd
#borrowing dataframe from @Alexendra
df = pd.DataFrame({
'col_1': [
['A', 'A', 'A', 'B', 'C'],
['D', 'B', 'C'],
['C'],
['A', 'A', 'A']
]
})
df['new_col'] = df['col_1'].map(lambda x : 1 if x[0:3] == ['A','A','A'] else 0)
print(df)
输出:
col_1 new_col
0 [A, A, A, B, C] 1
1 [D, B, C] 0
2 [C] 0
3 [A, A, A] 1
谢谢,返回一个错误:TypeError:“float”对象不适合你从NaN的?@khaledkoubaa-什么是print(df['col_1'].map(type))
?@khaledkoubaa-如果有字符串,则可以使用df['col_1']=df['col_1'].str.strip('[]').str.split(',')
,在我的列表解决方案之前
col_1 new_col
0 [A, A, A, B, C] 1
1 [D, B, C] 0
2 [C] 0
3 [A, A, A] 1