![](/img/trans.png)
[英]Openpyxl & Python - Combining data from cells in two columns into a single column
[英]Combining two columns with related data into a single column (python, pandas)
我正在尋找使用python中的pandas將兩列與.xlsx文件中的相關數據結合起來的正確邏輯。 它類似於該文章:將pandas中的2列合並為在python中具有數據的列 ,不同之處在於我還希望在合並列時轉換數據,因此這並不是兩列的真正合並。 我希望能夠說“如果在行x中wbc_na列的值是“ checked”,則在行x中的行x的下面放置“不可用”。 合並后,我想刪除“ wbc_na”列,因為“ wbc”現在包含我需要的所有信息。 例如:
input:
ID,wbc, wbc_na
1,9.0,-
2,NaN,checked
3,10.2,-
4,8.8,-
5,0,checked
輸出:
ID,wbc
1,9.0
2,Not available
3,10.2
4,8.8
5,Not available
感謝您的建議。
您可以使用loc
查找“ wbc_na”列的“檢查”位置,並為這些行分配“ wbc”列的值:
In [18]:
df.loc[df['wbc_na'] == 'checked', 'wbc'] = 'Not available'
df
Out[18]:
ID wbc wbc_na
0 1 9 -
1 2 Not available checked
2 3 10.2 -
3 4 8.8 -
4 5 Not available checked
[5 rows x 3 columns]
In [19]:
# now drop the extra column
df.drop(labels='wbc_na', axis=1, inplace=True)
df
Out[19]:
ID wbc
0 1 9
1 2 Not available
2 3 10.2
3 4 8.8
4 5 Not available
[5 rows x 2 columns]
您還可以使用列表解析來重新分配wbc列中的值:
data = pd.DataFrame({'ID': [1,2,3,4,5], 'wbc': [9, np.nan, 10, 8, 0], 'wbc_nan': ['-', 'checked', '-', '-', 'checked']})
data['wbc'] = [(item if data['wbc_nan'][x] != 'checked' else 'Not available') for x, item in enumerate(data['wbc'])]
data = data.drop('wbc_nan', axis=1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.