我有下表和代碼。我想創建兩個新列。1 標識帶有字母 YYY 的任何代碼,另一個標識字母 WWW,如中間表中所示。之后,我想匯總這些并有一個包含所有 YYY 代碼和 WWW 代碼及其總數的 ID 列。
我對python有點陌生。我正在嘗試進入下面的決賽桌,但我一直試圖進入中間桌并在下面提供了我的代碼。我收到一個 KeyError: 'code':
#for YYY
def categorise(y):
if y['Code'].str.contains('YYY'):
return 1
return 0
df1['Code'] = df.apply(lambda y: categorise(y), axis=1)
#for WWW
def categorise(w):
if w['Code'].str.contains('WWW'):
return 1
return 0
df1['Code'] = df.apply(lambda w: categorise(w), axis=1)
任何幫助將不勝感激。
當前表:
| 代碼 |
|---|
| 001,ABC,123,YYY |
| 002,ABC,546,萬維網 |
| 003,ABC,342,萬維網 |
| 004,ABC,635,YYY |
中間表:
| 代碼 | 位置_Y | 位置_W |
|---|---|---|
| 001,ABC,123,YYY | 1 | 0 |
| 002,ABC,546,萬維網 | 0 | 1 |
| 003,ABC,342,萬維網 | 0 | 1 |
| 004,ABC,635,YYY | 1 | 0 |
決賽桌:
| 身份證 | 位置_Y | 位置_W |
|---|---|---|
| 001,ABC,123,YYY - 004,ABC,635,YYY | 2 | 0 |
| 002,ABC,546,WWW - 003,ABC,342,WWW | 0 | 2 |
任何幫助,將不勝感激
uj5u.com熱心網友回復:
# assuming the string of interest is the last under the code column
df['id'] = df['Code'].str.rsplit(',', n=1, expand=True)[1]
# create columns with 1 or 0 if string exists in the Code
df['Location_Y'] = df['id'].eq('YYY').astype(int)
df['Location_W'] = df['id'].eq('WWW').astype(int)
# groupby to get the aggregates
df.groupby('id', as_index=False).agg({'Code' : ' - '.join,
'Location_Y': sum,
'Location_W': sum
})[['Code', 'Location_Y', 'Location_W']]
Code Location_Y Location_W
0 002,ABC,546,WWW - 003,ABC,342,WWW 0 2
1 001,ABC,123,YYY - 004,ABC,635,YYY 2 0
uj5u.com熱心網友回復:
提取最后一個元素,get_dummies。按元素分組并聚合獲取總和并根據需要加入。編碼如下
df=df.assign(coded=df['Code'].str.split('\,').str[-1])
#intermediate
df=df.assign(coded=df['Code'].str.split('\,').str[-1])
s = df.join(pd.get_dummies(df['coded']))
Code coded WWW YYY
0 001,ABC,123,YYY YYY 0 1
1 002,ABC,546,WWW WWW 1 0
2 003,ABC,342,WWW WWW 1 0
3 004,ABC,635,YYY YYY 0 1
#Final
s.groupby('coded').agg(**{'Code':('Code', lambda x: x.str.cat(sep='-')),'Y':('YYY', 'sum'),'W':('WWW', 'sum')}).reset_index().drop(columns='coded')
Code Y W
0 002,ABC,546,WWW-003,ABC,342,WWW 0 2
1 001,ABC,123,YYY-004,ABC,635,YYY 2 0
uj5u.com熱心網友回復:
好吧,與其他人不同,如果您是初學者,我建議您使用正則運算式并以更簡單的方式進行操作。
因此,對于中間表,請執行以下操作:
import pandas as pd
import re
df = pd.read_csv('test_table.csv')
yyy = []
www = []
for index, row in df.iterrows():
val_y = re.search('YYY', row['test data'])
if val_y is None:
yyy.append(0)
else:
yyy.append(1)
val_w = re.search('WWW', row['test data'])
if val_w is None:
www.append(0)
else:
www.append(1)
df['Location_Y'] = yyy
df['Location_W'] = www
print(df)
對于Final,像這樣更改for回圈
for index, row in df.iterrows():
val_y = row['test data'].count('YYY')
yyy.append(val_y)
val_w = row['test data'].count('WWW')
www.append(val_w)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/525444.html
標籤:Python熊猫
下一篇:如何計算列的重復不變符號?
