如何根据另一个数据框的条件创建新的数据框

alw*_*ons 7 python dataframe pandas

刚刚进入 Python,所以希望我不会在这里问一个愚蠢的问题......

所以我有一个名为“df_complete”的 Pandas 数据框,假设有 100 行,包含名为:“type”、“writer”、“status”、“col a”、“col c”的列。我想创建/更新一个名为“temp_df”的新数据框,并根据使用“df_complete”值的条件创建它。

temp_df = pandas.DataFrame()

if ((df_complete['type'] == 'NDD') & (df_complete['writer'] == 'Mary') & (df_complete['status'] != '7')):
    temp_df['col A'] = df_complete['col a']
    temp_df['col B'] = 'good'
    temp_df['col C'] = df_complete['col c']
Run Code Online (Sandbox Code Playgroud)

但是,当我这样做时,我收到以下错误消息:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Run Code Online (Sandbox Code Playgroud)

我阅读了这个线程并将我的“和”更改为“&”: 系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

我还在这里阅读了此线程以将所有内容放在括号中:将 dtyped [float64] 数组与 Pandas DataFrame 中类型为 [bool] 的标量进行比较

但是错误仍然存​​在。这是什么原因造成的?我该如何解决?

** 后续问题 ** 另外,如何获取满足条件的行的索引值?

jez*_*ael 5

我认为你需要boolean indexing使用ix仅选择列col acol c

temp_df = df_complete.ix[(df_complete['type'] == 'NDD') & 
                         (df_complete['writer'] == 'Mary') & 
                         (df_complete['status'] != '7'), ['col a','col c']]
#rename columns
temp_df = temp_df.rename(columns={'col a':'col A','col c':'col C'})
#add new column 
temp_df['col B'] = 'good'
#reorder columns
temp_df = temp_df[['col A','col B','col C']]
Run Code Online (Sandbox Code Playgroud)

样本:

df_complete = pd.DataFrame({'type':  ['NDD','NDD','NT'],
                            'writer':['Mary','Mary','John'],
                            'status':['4','5','6'],
                            'col a': [1,3,5],
                            'col b': [5,3,6],
                            'col c': [7,4,3]}, index=[3,4,5])

print (df_complete)
   col a  col b  col c status type writer
3      1      5      7      4  NDD   Mary
4      3      3      4      5  NDD   Mary
5      5      6      3      6   NT   John

temp_df = df_complete.ix[(df_complete['type'] == 'NDD') & 
                         (df_complete['writer'] == 'Mary') & 
                         (df_complete['status'] != '7'), ['col a','col c']]

print (temp_df)  
   col a  col c
3      1      7
4      3      4

temp_df = temp_df.rename(columns={'col a':'col A','col c':'col C'})
#add new column 
temp_df['col B'] = 'good'
#reorder columns
temp_df = temp_df[['col A','col B','col C']]
print (temp_df)  
   col A col B  col C
3      1  good      7
4      3  good      4
Run Code Online (Sandbox Code Playgroud)

  • ix 折旧了,因为这些年以后再看 (4认同)