我有两只熊猫数据(“铭文”和“地名”;在这两种情况下,一行是一个条目,文本和元数据保存在几个不同的列中)。我在找所有有地名的铭文。为此,我遍历地名(“地名”),然后遍历所有铭文(“文字”),寻找匹配项。
如果找到匹配项,我希望将整个铭文(整行)复制到一个新的dataframe (称为"matches",它的列与“铭文”相同),然后向它添加一些来自"placenames“dataframe的元素(例如,匹配的名称或GPS坐标)。
使用附加函数,这很容易实现:
for idx, elem in enumerate(placenames['names']):
for index, element in enumerate(inscriptions['text']):
if elem in element:
matches = matches.append(inscriptions.iloc[index], ignore_index=True)
matches.at[row, 'place'] = placenames['name'].iloc[idx]
matches.at[row, 'latitude'] = placenames['latitude'].iloc[idx]但是,由于不推荐使用frame.append方法,所以我想避免使用它,但我只是不能让它使用pd.concat()或其他任何东西:每当我尝试时,行不是写在下面,而是作为一个额外的列来写的,从而生成一个有大量空单元格的dataframe,对我来说非常无用。
有人知道我如何将上面的代码转换成一个非反对的变体吗?任何帮助都是非常感谢的,谢谢。
发布于 2022-08-09 21:36:07
单行是pandas.Series,concat()将其添加为列,但如果将行转换为pandas.DataFrame和转发器,则concat()将其添加为行。
它可以是这样的:
matches = pd.concat([matches, pd.DataFrame(inscriptions.iloc[index].T] )编辑:
最小工作示例(有其他更改)
import pandas as pd
placenames = pd.DataFrame({
'name': ['abc', 'xyz'],
'latitude': [1, 2],
})
inscriptions = pd.DataFrame({
'text': ['hello abc', 'bye xyz'],
})
matches = pd.DataFrame({
'text': ['text foo', 'text bar'],
'place': ['foo', 'bar'],
'latitude': [11, 12],
})
for idx_placenames, row_placenames in placenames.iterrows():
for idx_inscriptions, row_inscriptions in inscriptions.iterrows():
if row_placenames['name'] in row_inscriptions['text']:
row_inscriptions['place'] = row_placenames['name']
row_inscriptions['latitude'] = row_placenames['latitude']
#matches = matches.append(row_inscriptions, ignore_index=True)
matches = pd.concat([matches, pd.DataFrame(row_inscriptions).T ])
#matches = matches.reset_index(drop=True)
print(matches)https://stackoverflow.com/questions/73295641
复制相似问题