【发布时间】:2021-01-06 21:19:06
【问题描述】:
QID Questions B Answer1 Answer2 Answer3 F G H I J
0 3 a 4.0 a a a a e g i l
1 4 b 5.0 b b b a r h m p
2 5 d 5.0 NaN e d b u e i z
3 6 e 5.0 d h r b c z i 3
我想在df_1 的行之间添加another one, new_dataframe。
QID Questions B Answer1 Answer2 Answer3 F G H I J
2 4_1 z 5.0 b k b a r h m p
3 4_2 w 4.0 b k b c r h m p
确实,我想得到:
QID Questions B Answer1 Answer2 Answer3 F G H I J
0 3 a 4.0 a a a a e g i l
1 4 b 5.0 b b b a r h m p
2 4_1 z 5.0 b k b a r h m p
3 4_2 w 4.0 b k b c r h m p
4 5 d 5.0 NaN e d b u e i z
5 6 e 5.0 d h r b c z i 3
所以我想整合第二个数据帧new_dataframe 的行,其QID 由一个数字和一个子数字组成,跟随df1 的行。比如new_dataframe中QID为4_1、4_2...的行应该在4之后合并。
到目前为止,我尝试了以下方法:
# Now I would like to join this new dataframe with dataframe_1, respecting the index, sort it and so on.
for i, row in df1.iterrows():
qid = row['QID']
# test if there is such a QID in new_dataframe
repeated_question = new_dataframe[new_dataframe['QID'].split("_")[0] == qid]
# insert them
更新
我用实际数据尝试了 Trenton McKinney 的更新答案并得到了一个例外:
from natsort import index_natsorted as ins
import numpy as np
import pandas as pd
# read the files
df1 = pd.read_csv("/content/drive/My Drive/Auspex/QuestionBank_06082020_QGrid_and_CINT.csv", dtype={'QID': str}, low_memory=False)
df1.drop(columns=['Unnamed: 0'], inplace=True)
df2 = pd.read_csv('/content/drive/My Drive/Auspex/new_df.csv', dtype={'QID': str})
df2.drop(columns=['Unnamed: 0'], inplace=True)
# concat them
df = pd.concat([df1, df2])
# sort the values using the key parameter in sort_values
df.sort_values(by='QID', key=lambda col: np.argsort(ins(col))).reset_index(drop=True)
我明白了:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-18-d9f848d1f6bf> in <module>()
14
15 # sort the values using the key parameter in sort_values
---> 16 df.sort_values(by='QID', key=lambda col: np.argsort(ins(col))).reset_index(drop=True)
TypeError: sort_values() got an unexpected keyword argument 'key'
【问题讨论】:
标签: python python-3.x pandas string indexing